TypeError: setting getter-only property "x"

JavaScript 嚴格模式下,僅限嚴格模式的異常“設定僅有 getter 的屬性”發生於以下情況:嘗試為僅指定了 getter 的屬性設定新值,或者設定同樣僅定義了 getter 的私有訪問器屬性

訊息

TypeError: Cannot set property x of #<Object> which has only a getter (V8-based)
TypeError: '#x' was defined without a setter (V8-based)
TypeError: setting getter-only property "x" (Firefox)
TypeError: Attempted to assign to readonly property. (Safari)
TypeError: Trying to access an undefined private setter (Safari)

錯誤型別

TypeError 僅在嚴格模式下出現。

哪裡出錯了?

此錯誤發生於嘗試為僅指定了 getter 的屬性設定新值。在非嚴格模式下,此操作將被靜默忽略,但在嚴格模式下,它會丟擲 TypeError。類始終處於嚴格模式,因此給僅有 getter 的私有元素賦值總是會丟擲此錯誤。

示例

沒有 setter 的屬性

以下示例展示瞭如何為屬性設定 getter。它沒有指定 setter,因此在嘗試將 temperature 屬性設定為 30 時會丟擲 TypeError。有關更多詳細資訊,請參閱 Object.defineProperty() 頁面。

js
"use strict";

function Archiver() {
  const temperature = null;
  Object.defineProperty(this, "temperature", {
    get() {
      console.log("get!");
      return temperature;
    },
  });
}

const arc = new Archiver();
arc.temperature; // 'get!'

arc.temperature = 30;
// TypeError: setting getter-only property "temperature"

要解決此錯誤,您需要刪除嘗試設定 temperature 屬性的 arc.temperature = 30 行,或者您需要為它實現一個 setter,例如這樣:

js
"use strict";

function Archiver() {
  let temperature = null;
  const archive = [];

  Object.defineProperty(this, "temperature", {
    get() {
      console.log("get!");
      return temperature;
    },
    set(value) {
      temperature = value;
      archive.push({ val: temperature });
    },
  });

  this.getArchive = function () {
    return archive;
  };
}

const arc = new Archiver();
arc.temperature; // 'get!'
arc.temperature = 11;
arc.temperature = 13;
arc.getArchive(); // [{ val: 11 }, { val: 13 }]

另見