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";

另見