类型错误:无法重新定义不可配置的属性 "x"

当尝试重新定义属性但该属性是 non-configurable 时,会发生 JavaScript 异常 "无法重新定义不可配置的属性"。

¥The JavaScript exception "can't redefine non-configurable property" occurs when it was attempted to redefine a property, but that property is non-configurable.

信息

¥Message

TypeError: Cannot redefine property: "x" (V8-based)
TypeError: can't redefine non-configurable property "x" (Firefox)
TypeError: Attempting to change value of a readonly property. (Safari)

错误类型

¥Error type

TypeError

什么地方出了错?

¥What went wrong?

尝试重新定义属性,但该属性是 non-configurableconfigurable 属性控制是否可以从对象中删除该属性以及是否可以更改其属性(writable 除外)。通常,对象初始值设定项 创建的对象中的属性是可配置的。但是,例如,当使用 Object.defineProperty() 时,默认情况下该属性不可配置。

¥It was attempted to redefine a property, but that property is non-configurable. The configurable attribute controls whether the property can be deleted from the object and whether its attributes (other than writable) can be changed. Usually, properties in an object created by an object initializer are configurable. However, for example, when using Object.defineProperty(), the property isn't configurable by default.

示例

¥Examples

由 Object.defineProperty 创建的不可配置属性

¥Non-configurable properties created by Object.defineProperty

如果你未将它们指定为可配置,则 Object.defineProperty() 会创建不可配置的属性。

¥The Object.defineProperty() creates non-configurable properties if you haven't specified them as configurable.

js
const obj = Object.create({});
Object.defineProperty(obj, "foo", { value: "bar" });

Object.defineProperty(obj, "foo", { value: "baz" });
// TypeError: can't redefine non-configurable property "foo"

如果你打算稍后在代码中重新定义 "foo" 属性,则需要将其设置为可配置。

¥You will need to set the "foo" property to configurable, if you intend to redefine it later in the code.

js
const obj = Object.create({});
Object.defineProperty(obj, "foo", { value: "bar", configurable: true });
Object.defineProperty(obj, "foo", { value: "baz", configurable: true });

也可以看看