【问题标题】:Axios call always ending in then() callbackAxios 调用总是以 then() 回调结束
【发布时间】:2019-12-02 17:55:15
【问题描述】:

我正在调用这个触发 Axios 请求的 Vuex 操作,该请求被放入 try/catch 块中。

我这样称呼:

this.$store
  .dispatch('api/get', { url: url })
  .then(data => { console.log(data) })
  .catch(error => { console.log(error) })

Vuex 行动

async get({ commit }, payload) {
  try {
    let response = await this.$axios.get(payload.url, payload.data)
    return response.data
  } catch (e) {
    commit('notifications/PUSH_ALERT', {
      alert: e.response.data.message,
    })
  }
},

我的 API 返回错误,该错误在 catch {} 块中的 Vuex 操作中被拦截。

为什么仍然调用.then(response) 回调?当然是响应为空。

我希望.catch(error) 会被调用?

【问题讨论】:

  • 你正在使用 catch 块解决你的错误,所以它总是会转到 then 。为了在 api 调用中也出现错误,您应该在 catch blcok 中抛出错误

标签: vue.js axios vuex


【解决方案1】:

你可以像这样再次throw它:

async get({ commit }, payload) {
  try {
    let response = await this.$axios.get(payload.url, payload.data)
    return response.data
  } catch (e) {
    commit('notifications/PUSH_ALERT', {
      alert: e.response.data.message,
    })
    // Throw error again when it is handled, so outer catch can handle it too
    throw e
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    相关资源
    最近更新 更多