类型错误:设置仅 getter 属性 "x"

当尝试为仅指定了 getter 的属性设置新值时,会发生 JavaScript 严格模式-only 异常 "设置仅 getter 属性"。

¥The JavaScript strict mode-only exception "setting getter-only property" occurs when there is an attempt to set a new value to a property for which only a getter is specified.

信息

¥Message

TypeError: Cannot set property x of #<Object> which has only a getter (V8-based)
TypeError: setting getter-only property "x" (Firefox)
TypeError: Attempted to assign to readonly property. (Safari)

错误类型

¥Error type

仅限 严格模式 中的 TypeError

¥TypeError in strict mode only.

什么地方出了错?

¥What went wrong?

尝试为仅指定 getter 的属性设置新值。虽然这在非严格模式下会被默默地忽略,但它会在 严格模式 中抛出 TypeError

¥There is an attempt to set a new value to a property for which only a getter is specified. While this will be silently ignored in non-strict mode, it will throw a TypeError in strict mode.

示例

¥Examples

没有 setter 的属性

¥Property with no setter

下面的示例展示了如何为属性设置 getter。它没有指定 setter,因此在尝试将 temperature 属性设置为 30 时将抛出 TypeError。有关更多详细信息,另请参阅 Object.defineProperty() 页面。

¥The example below shows how to set a getter for a property. It doesn't specify a setter, so a TypeError will be thrown upon trying to set the temperature property to 30. For more details see also the Object.defineProperty() page.

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"

要修复此错误,你需要删除尝试设置温度属性的 arc.temperature = 30 行,或者你需要为其实现 setter,例如:

¥To fix this error, you will either need to remove the arc.temperature = 30 line, which attempts to set the temperature property, or you will need to implement a setter for it, for example like this:

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

也可以看看