You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express中调用listen方法时回调函数未定义问题排查

问题原因与解决方案

为什么出错?

你遇到的ReferenceError: onListenCallBack is not defined错误,核心原因有两个:

  1. 方法引用错误:类内部的实例方法不能直接裸写调用,必须通过this.方法名来引用。你直接写onListenCallBack,JS会把它当成全局变量查找,自然找不到。
  2. this指向丢失:就算你加上this,直接传this.onListenCallBack给listen,回调执行时this的指向会发生变化(默认指向全局对象或严格模式下的undefined),导致后续访问this.#app.port也会报错。

解决办法

办法一:用bind绑定this

通过bind把回调函数的this固定为当前类实例:

init() {
    this.#app.listen(this.#port, this.onListenCallBack.bind(this));
}

onListenCallBack() {
    console.log("Listening on port : " + this.#app.port);
}

办法二:用箭头函数包裹

箭头函数会继承外层作用域的this,直接用它包裹回调就能保留正确的指向:

init() {
    this.#app.listen(this.#port, () => this.onListenCallBack());
}

onListenCallBack() {
    console.log("Listening on port : " + this.#app.port);
}

办法三:构造函数提前绑定

在类的构造函数里提前把方法的this绑定好,后续直接传方法名就行:

constructor() {
    // 这里写你的其他初始化逻辑,比如初始化this.#app、this.#port
    this.onListenCallBack = this.onListenCallBack.bind(this);
}

init() {
    this.#app.listen(this.#port, this.onListenCallBack);
}

onListenCallBack() {
    console.log("Listening on port : " + this.#app.port);
}

内容的提问来源于stack exchange,提问作者WDUK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 01:44:56