javascript エラー「Uncaught TypeError: Cannot add property xxx, object is not extensible」の解決方法

javascript エラー「Uncaught TypeError: Cannot add property xxx, object is not extensible」の解決方法

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;
}