javascript エラー「Uncaught TypeError: Cannot add property xxx, object is not extensible」の解決方法
- 作成日 2022.05.30
- 更新日 2022.12.13
- javascript
- javascript

javascriptで、エラー「Uncaught TypeError: Cannot add property xxx, object is not extensible」が発生した場合の原因と解決方法を記述してます。厳格モード「use strict」を指定したときだけ発生します。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 108.0.5359.99
エラー内容
以下の「preventExtensions」でプロパティの追加を禁止するコードで発生。
'use strict';
const person = {
name: 'tanaka'
};
Object.preventExtensions(person);
person.age = 25;
エラーメッセージ
※このエラーは「use strict」を使用した厳格モードのみで発生します。
Uncaught TypeError: Cannot add property age, object is not extensible
画像

firefox(バージョン107)では、以下のエラーとなります。
Uncaught TypeError: can't define property "age": Object is not extensible
画像

原因
「preventExtensions」を使用して、プロパティの追加を禁止したあとに追加しているため
解決方法
禁止する前に追加するか、
'use strict';
const person = {
name: 'tanaka'
};
person.age = 25;
Object.preventExtensions(person);
「isExtensible」で禁止になっていないかを判定してから追加する
'use strict';
const person = {
name: 'tanaka'
};
Object.preventExtensions(person);
if(Object.isExtensible(person)){
person.age = 25;
}
-
前の記事
VBA 使用しているEXCELのバージョンを取得する 2022.05.29
-
次の記事
jquery 指定したhtmlタグの中にhtmlタグを挿入する 2022.05.30
コメントを書く