类型错误:属性 "x" 不可配置且无法删除

当尝试删除属性但该属性是 non-configurable 时,会发生 JavaScript 异常 "属性不可配置且无法删除"。

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

信息

¥Message

TypeError: Cannot delete property 'x' of #<Object> (V8-based)
TypeError: property "x" is non-configurable and can't be deleted (Firefox)
TypeError: Unable to delete property. (Safari)

错误类型

¥Error type

TypeError 仅在严格模式下。

¥TypeError in strict mode only.

什么地方出了错?

¥What went wrong?

尝试删除属性,但该属性是 non-configurableconfigurable 属性控制是否可以从对象中删除该属性以及是否可以更改其属性(writable 除外)。

¥It was attempted to delete 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.

此错误仅发生在 严格模式代码 中。在非严格代码中,该操作返回 false

¥This error happens only in strict mode code. In non-strict code, the operation returns false.

示例

¥Examples

尝试删除不可配置的属性

¥Attempting to delete non-configurable properties

不可配置的属性并不常见,但可以使用 Object.defineProperty()Object.freeze() 创建它们。

¥Non-configurable properties are not super common, but they can be created using Object.defineProperty() or Object.freeze().

js
"use strict";
const obj = Object.freeze({ name: "Elsa", score: 157 });
delete obj.score; // TypeError
js
"use strict";
const obj = {};
Object.defineProperty(obj, "foo", { value: 2, configurable: false });
delete obj.foo; // TypeError
js
"use strict";
const frozenArray = Object.freeze([0, 1, 2]);
frozenArray.pop(); // TypeError

JavaScript 中还内置了一些不可配置的属性。也许你尝试删除一个数学常数。

¥There are also a few non-configurable properties built into JavaScript. Maybe you tried to delete a mathematical constant.

js
"use strict";
delete Math.PI; // TypeError

也可以看看