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

Vue.js异步方法中如何正确访问this?

Vue.js异步方法中this指向问题的解决办法

问题原因拆解

  • 第一个报错Unexpected reserved word 'await':使用await的方法必须声明为async,普通方法直接用await不符合JavaScript语法规则。
  • 第二个报错Cannot read properties of undefined (reading 'book'):箭头函数不会绑定自身的this,在Vue组件的methods中使用箭头函数时,this无法指向组件实例,自然无法读取实例上的book属性。

正确代码写法

不要用箭头函数,直接给普通方法添加async关键字即可,这样this会正常指向Vue组件实例:

如果方法需要接收外部参数:

methods: {
  async playRecording(path) {
    return await this.getAudioUrl(path)
  }
}

如果方法要访问组件自身的book属性:

methods: {
  async playRecording() {
    const path = '/recordings/' + this.book
    return await this.getAudioUrl(path)
  }
}

核心注意点

Vue组件的methods必须使用普通函数声明(或函数表达式),不能用箭头函数,这样Vue才能自动将this绑定到组件实例上。只要给方法加上async关键字,就能在方法内部正常使用await调用异步函数,同时this的指向完全正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 03:54:28