JavaScript 报错解析:TypeError: undefined is not a function
Taimili 艾米莉 ( 一款免费开源的 taimili.com )
艾米莉 是一款优雅便捷的 GitHub Star 管理和加星工具,基于 PHP & javascript 构建, 能对github 得 star fork follow watch 管理和提升,最适合github 的深度用户
作者:开源之眼
链接:juejin.cn/post/755019…
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
在日常前端开发中,我们经常会遇到类似这样的报错信息:
TypeError: undefined is not a function
初看可能有点懵:为什么一个变量突然就不是函数了?本文将详细拆解该错误出现的原因、常见场景以及如何快速定位和解决。
一、错误的含义
在 JavaScript 中,函数是一等公民,可以作为变量、参数、返回值来使用。当你调用一个变量并在其后面加上括号 () 时,JavaScript 会尝试把它当作函数执行。
例如:
let foo = 123;
foo(); // ❌ TypeError: foo is not a function
这里 foo 是 number 类型,不是函数,因此调用 foo() 会触发 TypeError: ... is not a function。
当变量的值为 undefined 时,错误信息就变成了 undefined is not a function。
二、常见触发场景
1. 调用了未定义的函数
myFunc(); // ❌ ReferenceError 或 TypeError
如果变量 myFunc 存在但值为 undefined,会触发 TypeError。
2. API 不兼容或方法不存在
不同浏览器、Node 版本或运行环境中,有些 API 并不存在:
document.getElementsByClassName('box').forEach(el => {
console.log(el);
});
上例中,getElementsByClassName 返回的是 HTMLCollection,没有 forEach 方法,执行时会报:
TypeError: HTMLCollection.forEach is not a function
3. this 绑定错误
class Person {
constructor(name) {
this.name = name;
}
say() {
console.log(this.name);
}
}
const p = new Person("Alice");
const fn = p.say;
fn(); // ❌ TypeError: Cannot read properties of undefined
因为 this 丢失,导致方法执行出错。
4. 异步加载或模块未正确引入
import { doSomething } from './utils.js';
doSomething(); // 如果 utils.js 中没有导出 doSomething -> TypeError
三、排查思路
-
确认变量是否存在 使用
console.log(typeof variable)或console.log(variable)检查。 -
确认类型是否正确 在调用前判断:
if (typeof myFunc === "function") { myFunc(); } -
检查运行环境差异 某些 API 在 Node.js 和浏览器中不通用,或仅在新版本支持。
-
检查 this 上下文 如果是类方法或对象方法,注意绑定:
btn.addEventListener("click", p.say.bind(p));
四、解决方法示例
✅ 正确调用数组方法
Array.from(document.getElementsByClassName('box'))
.forEach(el => console.log(el));
✅ 绑定 this
const fn = p.say.bind(p);
fn(); // Alice
✅ 模块导入检查
确保 export 与 import 对应:
// utils.js
export function doSomething() {
console.log("done");
}
✅ 提前检查类型
if (typeof callback === "function") {
callback();
} else {
console.warn("callback 不是函数");
}
TypeError: undefined is not a function 本质上是 “把非函数的东西当函数调用了”。
常见原因有:
- 调用了未定义的方法或 API 不存在
this丢失,导致方法未正确绑定- 异步加载或模块导入错误
- 类型判断不严谨
解决思路是:检查变量是否存在 → 确认其类型 → 排查上下文与环境差异 → 添加防御性代码。