TypeError: can't assign to property "x" on "y": not an object

JavaScript 严格模式异常“无法为属性赋值”发生在尝试对原始值(例如符号字符串数字布尔值)创建属性时。原始值不能包含任何属性

消息

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)

错误类型

TypeError.

哪里出错了?

严格模式下,尝试对原始值(例如符号字符串数字布尔值)创建属性时,会抛出TypeError原始值不能包含任何属性

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

示例

无效案例

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

修复问题

要么修复代码以防止在这些地方使用原始值,要么通过创建等效的Object来解决问题。

js
"use strict";

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

另见