类型错误:WeakSet 键/WeakMap 值 'x' 必须是对象或未注册的符号

当无效类型的值用作 WeakSet 中的键或 WeakMap 中的值时,会发生 JavaScript 异常 "WeakSet 键(或 WeakMap 值)'x' 必须是对象或未注册的符号"。

¥The JavaScript exception "WeakSet key (or WeakMap value) 'x' must be an object or an unregistered symbol" occurs when an value of invalid type is used as a key in a WeakSet or as a value in a WeakMap.

信息

¥Message

TypeError: Invalid value used as weak map key (V8-based)
TypeError: WeakMap key 1 must be an object or an unregistered symbol (Firefox)
TypeError: WeakMap keys must be objects or non-registered symbols (Safari)

TypeError: Invalid value used in weak set (V8-based)
TypeError: WeakSet value 1 must be an object or an unregistered symbol (Firefox)
TypeError: WeakSet values must be objects or non-registered symbols (Safari)

错误类型

¥Error type

TypeError

什么地方出了错?

¥What went wrong?

WeakSetWeakMap 要求键是可垃圾回收的。只有对象和非注册符号(即 Symbol.for() 未返回的 symbols)才有效。欲了解更多信息,请参阅 内存管理。如果你想添加字符串、数字或其他原始值的键,则应将它们存储在常规 SetMap 中。

¥WeakSet and WeakMap require the keys to be garbage collectable. Only objects and non-registered symbols (that is, symbols not returned by Symbol.for()) are valid. For more information, see Memory management. If you want to add keys that are strings, numbers, or other primitive values, you should store them in a regular Set or Map instead.

示例

¥Examples

无效案例

¥Invalid cases

js
new WeakSet().add(1); // TypeError
new WeakMap().set(1, {}); // TypeError
new WeakSet([1]); // TypeError
new WeakMap([[1, {}]]); // TypeError

有效案例

¥Valid cases

js
new WeakSet().add({}); // OK
new WeakMap().set({}, 1); // OK

new Set([1]); // OK
new Map([[1, {}]]); // OK

也可以看看