javascript エラー「Uncaught TypeError: Cannot redefine property: xxx」の解決方法

javascript エラー「Uncaught TypeError: Cannot redefine property: xxx」の解決方法

javascriptで、エラー「Uncaught TypeError: Cannot redefine property: xxx」が発生した場合の原因と解決方法を記述してます。厳格モード「use strict」のみで発生します。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 108.0.5359.99

エラー内容

以下のオブジェクトの値を変更しようとしたコードで発生。

'use strict';

const obj = {
  hoge: 1
};

Object.defineProperty(obj, 'hoge', {
  value: 2,
  writable: true,
  configurable: false // 属性の変更およびプロパティ削除禁止
});

Object.defineProperty(obj, 'hoge', {
  value: 3,
  writable: true, 
  configurable: true // 属性の変更およびプロパティ削除禁止
});

エラーメッセージ
※このエラーは「use strict」を使用した厳格モードのみで発生します。

Uncaught TypeError: Cannot redefine property: hoge
    at Function.defineProperty (<anonymous>)

画像

firefox(バージョン107)では、以下のエラーとなります。

Uncaught TypeError: can't redefine non-configurable property "hoge"

画像

原因

「configurable」が「false」に設定されているため

解決方法

「true」にした上で、実行する

'use strict';

const obj = {
  hoge: 1
};

Object.defineProperty(obj, 'hoge', {
  value: 2,
  writable: true,
  configurable: true // 属性の変更およびプロパティ削除禁止
});

Object.defineProperty(obj, 'hoge', {
  value: 3,
  writable: true, // 書き換え禁止
  configurable: true // 属性の変更およびプロパティ削除禁止
});

console.log(obj.hoge)

実行結果