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

Nuxt的asyncData方法调用@nuxtjs/toast报错Toast未定义如何解决

报错原因

  • asyncData 是 Nuxt 专属的生命周期钩子,执行时机在组件实例初始化之前,钩子内部无法访问组件实例 this,所以调用 this.toast 时this为undefined,直接抛出找不到属性的错误。
  • 额外注意:你在mounted中正常调用的写法是this.$toast,哪怕能拿到this,少写了前缀$的this.toast也无法正常调用。

正确调用方法

asyncData的入参中自带全局app实例,Nuxt注册的所有全局插件都会挂载到app对象上,@nuxtjs/toast注册后对应的调用入口是app.$toast,直接使用该对象调用toast方法即可。

修改后的代码示例:

async asyncData({ $axios, route, app}) {
  const [blogPost, blogCategoryPosts] = await Promise.all([
      $axios.get(`${process.env.API_DOMAIN}/api/blog/posts${route.path}`).then(response => response.data).catch(error => {}),
      $axios.get(`${process.env.API_DOMAIN}/api/blog/categories${route.path}`).then(response => response.data).catch(error => {}),
  ])

  if(blogPost == undefined && blogCategoryPosts == undefined) {
    // 替换原有this.toast为app.$toast即可
    app.$toast.error('Error')
  }

  return {
    blogPost: blogPost,
    blogCategoryPosts: blogCategoryPosts,
    locale: app.i18n.locale
  }
},

补充说明

如果你的项目开启了服务端渲染(SSR),asyncData会先在服务端执行一次,此时调用app.$toast属于客户端UI API,不会在用户侧弹出提示。如果要保证提示必然触发,可以把判断结果存在返回值里,在mounted钩子中判断后再调用toast:

// asyncData 部分修改
async asyncData({ $axios, route, app}) {
  const [blogPost, blogCategoryPosts] = await Promise.all([
      $axios.get(`${process.env.API_DOMAIN}/api/blog/posts${route.path}`).then(response => response.data).catch(error => {}),
      $axios.get(`${process.env.API_DOMAIN}/api/blog/categories${route.path}`).then(response => response.data).catch(error => {}),
  ])
  const isContentEmpty = !blogPost && !blogCategoryPosts
  return {
    blogPost,
    blogCategoryPosts,
    locale: app.i18n.locale,
    // 新增状态字段返回
    isContentEmpty
  }
},
// mounted 部分新增判断
mounted() {
  if (this.isContentEmpty) {
    this.$toast.error('Error')
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:36:03