首页 > 解决方案 > Vuex 动作没有抛出 axios try/catch

问题描述

我正在使用 Vue 和 Vuex,并且希望能够在我的组件中显示 API 错误,当这些错误发生在我的操作中时。我在这个例子中使用 axios。

这是应该只执行获取请求并在失败时抛出错误的操作

export default {
  async search({ commit }, params) {
    const result = await axios.get(`http://localhost:3000/search`, params)
    commit('SET_RESULTS', result.data)
  }
}

这是我的 Search.vue 组件,当我的操作中发生 api 错误时,我希望能够记录“捕获的错误”

methods: {
    onSubmit() {
      try {
        this.$store.dispatch('search', this.value)
      } catch (e) {
        console.log('Caught Error')
      }
    }
  }

我确实收到红色控制台错误,但不是我在 Search.vue 中定义的错误。所以由于某种原因,我的动作没有抛出,或者我的 Search.vue 没有捕捉到。

标签: javascriptvue.jsvuex

解决方案


dispatch返回一个承诺,它不会抛出错误。

所以你会使用catch回调:

this.$store.dispatch('search', this.value).catch(err => {
  console.log('Caught Error')
}).

如果您想要try/ catch,那么您需要在该承诺上使用async/ :await

async onSubmit() {
  try {
    await this.$store.dispatch('search', this.value)
  } catch (e) {
    console.log('Caught Error')
  }
}

推荐阅读