TypeError: "x" is not a function

JavaScript 异常“不是函数”发生在尝试从函数调用值时,但该值实际上不是函数。

消息

TypeError: "x" is not a function. (V8-based & Firefox & Safari)

错误类型

TypeError

哪里出错了?

它尝试从函数中调用值,但该值实际上不是函数。某些代码期望您提供一个函数,但您没有提供。

函数名可能有拼写错误?您调用方法的对象可能没有此函数?例如,JavaScript 的 Objects 没有 map 函数,但 JavaScript 的 Array 对象有。

有许多内置函数需要(回调)函数。您必须提供一个函数才能使这些方法正常工作。

示例

函数名中有拼写错误

在这种情况下,方法名中有拼写错误,这种情况经常发生。

js
const x = document.getElementByID("foo");
// TypeError: document.getElementByID is not a function

正确的函数名是 getElementById

js
const x = document.getElementById("foo");

在错误的对象上调用函数

对于某些方法,您必须提供一个(回调)函数,并且它仅适用于特定对象。在此示例中,使用了 Array.prototype.map(),它仅适用于 Array 对象。

js
const obj = { a: 13, b: 37, c: 42 };

obj.map((num) => num * 2);

// TypeError: obj.map is not a function

改用数组

js
const numbers = [1, 4, 9];

numbers.map((num) => num * 2); // [2, 8, 18]

函数与已存在的属性同名

有时在创建类时,您可能有一个同名的属性和一个函数。在调用函数时,编译器会认为该函数不再存在。

js
function Dog() {
  this.age = 11;
  this.color = "black";
  this.name = "Ralph";
  return this;
}

Dog.prototype.name = function (name) {
  this.name = name;
  return this;
};

const myNewDog = new Dog();
myNewDog.name("Cassidy"); // TypeError: myNewDog.name is not a function

改用不同的属性名

js
function Dog() {
  this.age = 11;
  this.color = "black";
  this.dogName = "Ralph"; // Using this.dogName instead of .name
  return this;
}

Dog.prototype.name = function (name) {
  this.dogName = name;
  return this;
};

const myNewDog = new Dog();
myNewDog.name("Cassidy"); // Dog { age: 11, color: 'black', dogName: 'Cassidy' }

使用括号进行乘法运算

在数学中,您可以将 2 × (3 + 5) 写成 2*(3 + 5) 或直接写成 2(3 + 5)。

使用后者会抛出错误

js
const sixteen = 2(3 + 5);
console.log(`2 x (3 + 5) is ${sixteen}`);
// Uncaught TypeError: 2 is not a function

您可以通过添加 * 运算符来纠正代码

js
const sixteen = 2 * (3 + 5);
console.log(`2 x (3 + 5) is ${sixteen}`);
// 2 x (3 + 5) is 16

正确导入导出的模块

确保您正确导入了模块。

一个示例辅助库 (helpers.js)

js
function helpers() {}

helpers.groupBy = function (objectArray, property) {
  return objectArray.reduce((acc, obj) => {
    const key = obj[property];
    acc[key] ??= [];
    acc[key].push(obj);
    return acc;
  }, {});
};

export default helpers;

正确的导入用法 (App.js)

js
import helpers from "./helpers";

另见