Skip to content

TypeError: x 是不 函数

错误信息

                x 是不 函数
              

快速摘要

你 used parentheses 到 call 值, 但那个值 是不 函数 — 它's 数字, 字符串, 对象, or `undefined`.

为什么发生

  • 属性 or 方法 name 是 misspelled (e.g., arr.legnth() 相反的 arr.长度)

  • 值是 undefined or 空 因为 lookup or API call 失败

  • 构建-in 方法是 overridden or 对象是 错误类型

最小示例

✗ 错误代码
const num = 5;
num();
✓ 修复代码
const fn = () => 5;
fn();

编号 是数字, 不函数 — calling 它使用 () throws TypeError. Assign 函数相反.

如何诊断

  • Log 值 and 它的类型使用 console.log(typeof 值) 之前 call

  • 检查如果函数 exists on 对象使用 typeof obj.方法

  • 验证对象是 类型你 expect 它到 是

如何修复

  • Fix 方法 name 到 match 真实方法 (e.g., 长度, 不 legnth)

  • Ensure 值是 actually 函数之前 calling 它

  • 检查那个对象是 正确类型之前 calling 它的方法

如何预防

  • Use typeof 检查之前 calling uncertain 函数

  • Use TypeScript 到 catch 类型 mismatches at 编译时间

相关资源

相关术语

相关课程

  • 函数

    学习如何 JavaScript 函数工作

相关练习

← 返回语言