类型错误:"x" 不是非空对象

当某个地方需要一个对象但未提供时,就会发生 JavaScript 异常 "不是非空对象"。null 不是一个对象并且不会工作。

¥The JavaScript exception "is not a non-null object" occurs when an object is expected somewhere and wasn't provided. null is not an object and won't work.

信息

¥Message

TypeError: Property description must be an object: x (V8-based)
TypeError: Property descriptor must be an object, got "x" (Firefox)
TypeError: Property description must be an object. (Safari)

TypeError: Invalid value used in weak set (V8-based)
TypeError: WeakSet value must be an object, got "x" (Firefox)
TypeError: Attempted to add a non-object value to a WeakSet (Safari)

错误类型

¥Error type

TypeError

什么地方出了错?

¥What went wrong?

某处需要一个对象但未提供。null 不是一个对象并且不会工作。你必须在给定情况下提供适当的对象。

¥An object is expected somewhere and wasn't provided. null is not an object and won't work. You must provide a proper object in the given situation.

示例

¥Examples

预期属性描述符

¥Property descriptor expected

当使用 Object.create()Object.defineProperty()Object.defineProperties() 等方法时,可选描述符参数需要一个属性描述符对象。不提供任何对象(例如仅提供数字),将引发错误:

¥When methods like Object.create() or Object.defineProperty() and Object.defineProperties() are used, the optional descriptor parameter expects a property descriptor object. Providing no object (like just a number), will throw an error:

js
Object.defineProperty({}, "key", 1);
// TypeError: 1 is not a non-null object

Object.defineProperty({}, "key", null);
// TypeError: null is not a non-null object

有效的属性描述符对象可能如下所示:

¥A valid property descriptor object might look like this:

js
Object.defineProperty({}, "key", { value: "foo", writable: false });

WeakMap 和 WeakSet 对象需要对象或符号键

¥WeakMap and WeakSet objects require object or symbol keys

WeakMapWeakSet 对象存储对象或符号键。你不能使用其他类型作为键。

¥WeakMap and WeakSet objects store object or symbol keys. You can't use other types as keys.

js
const ws = new WeakSet();
ws.add("foo");
// TypeError: "foo" is not a non-null object

使用对象代替:

¥Use objects instead:

js
ws.add({ foo: "bar" });
ws.add(window);

也可以看看