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

beforeRouteUpdate调用this.getData()报TypeError错误求助

解决Vue中beforeRouteUpdate调用this.getData()时报错"TypeError: this.getData is not a function"

问题原因

在Vue 2的组件内路由守卫beforeRouteUpdate中,若直接将钩子定义为async函数,可能会出现this指向异常的情况(尽管理论上普通async函数应保留正确的this绑定,但实际场景中可能因Vue内部的钩子处理逻辑导致this丢失),从而无法找到methods中定义的getData方法。

解决方法

方法一:改用普通钩子函数+内部自执行async箭头函数

将beforeRouteUpdate改为普通函数,内部通过自执行的async箭头函数处理异步逻辑,箭头函数会继承外部普通函数的this(即组件实例),确保能正确调用getData:

<script>
export default {
  beforeRouteUpdate(to, from, next) {
    (async () => {
      await this.getData()
      next()
    })()
  },
  data() {
    return {
      word: null,
    }
  },
  async created() {
    await this.getData()
  },
  methods: {
    async getData() {
      const resp = await axios.get(
        'http://127.0.0.1:8000/api/word/' + this.$route.params.word,
        { validateStatus: false }
      )

      console.log(resp)
      switch (resp.status) {
        case 200:
          this.word = {
            word: resp.data.word,
            definition: resp.data.definition,
          }
          break
        case 404:
          this.word = null
          break
      }
    },
  },
}
</script>

方法二:验证this指向(调试用)

如果坚持使用async作为钩子函数前缀,可以先打印this确认是否为组件实例,排查是否存在其他绑定问题:

<script>
export default {
  async beforeRouteUpdate(to, from, next) {
    // 打印this确认是否为组件实例
    console.log(this)
    await this.getData()
    next()
  },
  // ... 其他代码不变
}
</script>

额外说明

在beforeRouteUpdate触发时,this.$route.params已经更新为目标路由的参数,因此你的getData方法中直接使用this.$route.params.word是正确的,无需额外传递参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:35:50