异步async方法中如何引用类变量?this指向undefined报错怎么修复
问题原因
this.verificationCode 为 undefined 是类方法的 this 指向丢失导致的。当你直接把 sendCode 方法作为路由回调函数传递时,方法被调用时的执行上下文不再指向 VerificationCodeController 的实例,自然无法读取到实例上挂载的 verificationCode 属性。
修复方案
你可以选择以下任意一种方案解决:
- 方案1:在构造函数中提前绑定方法的this指向
class VerificationCodeController{ constructor(){ this.verificationCode = generateCode() // 新增这行完成this绑定 this.sendCode = this.sendCode.bind(this) } async sendCode(req, res){ await sendEmail(req.body.email, this.verificationCode) return res.json(responseCreator.response(this.verificationCode)); } }
- 方案2:用箭头函数定义类方法,自动继承实例上下文的this指向
class VerificationCodeController{ constructor(){ this.verificationCode = generateCode() } // 改为箭头函数写法 sendCode = async (req, res) => { await sendEmail(req.body.email, this.verificationCode) return res.json(responseCreator.response(this.verificationCode)); } }
- 方案3:注册路由时手动绑定this
如果你使用Express等类库注册路由,在传递回调时绑定实例即可:
const verificationController = new VerificationCodeController() // 绑定实例对应的this app.post('/send-code', verificationController.sendCode.bind(verificationController))
内容的提问来源于stack exchange,提问作者LeoSAN
相关产品推荐
相关产品推荐

