【问题标题】:Vuex action not throwing on axios try/catchVuex 动作没有抛出 axios try/catch
【发布时间】:2020-08-14 09:39:01
【问题描述】:

我正在使用 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 没有捕捉到。

【问题讨论】:

  • dispatch 返回一个承诺,它不会抛出错误。所以你会使用this.$store.dispatch(...).catch(err => { ... })。如果您想使用try/catch,那么您需要在该承诺上使用async/awaitawait this.$store.dispatch(...)
  • @skirtle 你能从中得出一个答案吗?所以我可以接受它

标签: javascript vue.js vuex


【解决方案1】:

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')
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    相关资源
    最近更新 更多