类型错误:无法分配给 "y" 上的属性 "x":不是一个对象

当尝试在 primitive 值(例如 symbolstringnumberboolean)上创建属性时,会发生 JavaScript 严格模式异常 "无法分配给属性"。原始 值不能容纳任何 property

¥The JavaScript strict mode exception "can't assign to property" occurs when attempting to create a property on primitive value such as a symbol, a string, a number or a boolean. Primitive values cannot hold any property.

信息

¥Message

TypeError: Cannot create property 'x' on number '1' (V8-based)
TypeError: can't assign to property "x" on 1: not an object (Firefox)
TypeError: Attempted to assign to readonly property. (Safari)

错误类型

¥Error type

TypeError

什么地方出了错?

¥What went wrong?

严格模式 中,当尝试在 primitive 值(例如 symbolstringnumberboolean)上创建属性时,会引发 TypeError原始 值不能容纳任何 property

¥In strict mode, a TypeError is raised when attempting to create a property on primitive value such as a symbol, a string, a number or a boolean. Primitive values cannot hold any property.

问题可能是意外值在意外位置流动,或者需要 StringNumber 的对象变体。

¥The problem might be that an unexpected value is flowing at an unexpected place, or that an object variant of a String or a Number is expected.

示例

¥Examples

无效案例

¥Invalid cases

js
"use strict";

const foo = "my string";
// The following line does nothing if not in strict mode.
foo.bar = {}; // TypeError: can't assign to property "bar" on "my string": not an object

解决问题

¥Fixing the issue

修复代码以防止在此类地方使用 primitive,或者通过创建等效的对象 Object 来修复问题。

¥Either fix the code to prevent the primitive from being used in such places, or fix the issue by creating the object equivalent Object.

js
"use strict";

const foo = new String("my string");
foo.bar = {};

也可以看看