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 = {};