vue.js - Nuxt fetch 中的 Vuex 操作 "not a function"

标签 vue.js vuex nuxt.js

我刚刚为我的 Nuxt 页面之一引入了错误处理,显然该操作在 fetch 内部映射和调用引发非函数错误。如果try/catch块不在那里它按预期工作并且根本没有错误。
这是我的组件剥离到基本部分:

export default {
  name: 'ViewArticle',
  async fetch ({ error }) {
    try {
      await this.fetchArticle({ articleSlug: this.articleSlug })
    } catch (err) {
      error({ statusCode: 404, message: 'May the force be with you' })
    }
  },
  computed: {
    ...mapGetters({
      article: 'article/single'
    }),
    articleSlug () {
      return this.$route.params.articleSlug
    }
  },
  methods: {
    ...mapActions({
      fetchArticle: 'article/fetchOne'
    })
  }
}
我假设 mapActions 以某种方式只在 spiel 稍后执行,但无法弄清楚如何防止错误。这样,基本上每次我加载页面时,它都会立即重定向到错误页面。
我收到的错误消息如下。显然fetchArticle是一个函数,除非它在 ​​try 内/catch块,它按预期工作。
this.fetchArticle is not a function                                                                                                               03:30:51

  at Object.fetch (52.js:32:18)
  at server.js:2881:39
  at Array.map (<anonymous>)
  at module.exports../.nuxt/server.js.__webpack_exports__.default (server.js:2864:51)

最佳答案

Fetch 提供了 context作为论据。

fetch(context)
在上下文中,我们可以找到我们的商店。在这里您可以查看上下文包含哪些内容:https://nuxtjs.org/api/context
fetch(context) {
   let store = context.store;
}
人们喜欢破坏它
fetch({ store }) {}
您的代码应如下所示:
  async fetch ({ error, store }) {
    try {
      await store.dispatch('article/fetchOne', { articleSlug: this.articleSlug })
    } catch (err) {
      error({ statusCode: 404, message: 'May the force be with you' })
    }
  },
获取在服务器端执行,这就是为什么你得到 is not an function错误。它的未定义

... fetch is called on server-side...

关于vue.js - Nuxt fetch 中的 Vuex 操作 "not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64218232/

相关文章:

javascript - Vue.js 条件模块样式

javascript - 如何清除 vuejs 状态的Interval

javascript - 从 Nuxt 配置文件提供资源

javascript - 如何在 Nuxt-js 方法中路由空白页面?

css - vue-路由器 : how to remove underline from router-link

javascript - TypeScript 无法检测 *.vue 文件

javascript - Vue.js - 当用户单击组件之外的位置时显示表单错误

vue.js - 从 vuex 操作访问 $root 实例

vue.js - 如何解决 Uncaught (in promise) TypeError : orders. forEach is not a function? Vue.JS 2

vue.js - 为什么我的 Nuxt/vue 页面被 robots.txt 屏蔽了?