javascript - 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 没有捕捉到。
解决方案
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')
}
}
推荐阅读
- reactjs - React Native 如何在应用程序中保存图像?
- c - 构建 FreeRDP 并安装错误:字段“des3_ctx”的类型不完整
- linux - 恢复无限嵌套/递归的 tmux 会话?
- c++ - 读取文件到 istream 替换类变量
- java - LibGDX 浮动与相机位置导致黑线与平铺地图
- java - 检查下一个要保存的输入是否在这些范围内
- class - fortran中的多态性
- android - 在 Android 生命周期中我应该在哪里使用 getIntent()
- python - if 函数的迭代器返回错误
- rust - 有没有办法在 Option 中拆分变量而不必使用 if 语句?