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。原始值不能包含任何属性。
示例
无效案例
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 = {};