javascript エラー「TypeError: Attempting to change configurable attribute of unconfigurable property.」の解決方法

javascript エラー「TypeError: Attempting to change configurable attribute of unconfigurable property.」の解決方法

javascriptで、エラー「TypeError: Attempting to change configurable attribute of unconfigurable property.」が発生した場合の原因と解決方法を記述してます。

環境

  • OS macOS Monterey
  • ブラウザ safari 15.5

エラー内容

以下のコードを実行時に発生。

'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」を使用した厳格モードのみで発生します。

TypeError: Attempting to change configurable attribute of unconfigurable property.

画像

原因

属性の変更およびプロパティ削除禁止である「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)

実行結果