TypeError: "x" is (not) "y"

JavaScript 异常“x 是(不是)y”在出现意外类型时发生。通常是意外的 undefinednull 值。

消息

TypeError: Cannot read properties of undefined (reading 'x') (V8-based)
TypeError: "x" is undefined (Firefox)
TypeError: "undefined" is not an object (Firefox)
TypeError: undefined is not an object (evaluating 'obj.x') (Safari)

TypeError: "x" is not a symbol (V8-based & Firefox)
TypeError: Symbol.keyFor requires that the first argument be a symbol (Safari)

错误类型

TypeError.

哪里出错了?

出现了一个意外的类型。这通常发生在 undefinednull 值上。

此外,某些方法,例如 Object.create()Symbol.keyFor(),需要提供特定的类型。

示例

无效案例

你不能在 undefinednull 变量上调用方法。

js
const foo = undefined;
foo.substring(1); // TypeError: foo is undefined

const foo2 = null;
foo2.substring(1); // TypeError: foo2 is null

某些方法可能需要特定类型。

js
const foo = {};
Symbol.keyFor(foo); // TypeError: foo is not a symbol

const foo2 = "bar";
Object.create(foo2); // TypeError: "foo2" is not an object or null

解决问题

要修复指向 undefinednull 值的空指针,你可以首先测试该值是否为 undefinednull

js
if (foo !== undefined && foo !== null) {
  // Now we know that foo is defined, we are good to go.
}

或者,如果你确信 foo 不会是另一个 假值(例如 ""0),或者过滤掉这些情况不是问题,你可以简单地测试它的真值性。

js
if (foo) {
  // Now we know that foo is truthy, it will necessarily not be null/undefined.
}

另见