Vuex 行动不等完成 axios 承诺



我在Laravel + VueJS/Vuex堆栈中开发应用程序时遇到了一个奇怪的情况。

我知道,如果没有返回承诺,调用它的父函数将不会等待它解决,因此事情将异步进行。默认情况下,Axios 在通过 http 调用资源时返回一个承诺。

所以我有父函数,看起来像这样:

fetchInvoiceSeries() {
var arr = []
let invsrs = this.$store.getters['getInvoiceSeries']
if (invsrs == null) {
return this.$store
.dispatch('get_invoice_series')
.then(() => {
invsrs = this.$store.getters['getInvoiceSeries']
if (invsrs != null) {
invsrs.forEach(function(s) {
arr.push({
value: s.id,
text: s.series + ' / ' + s.increment
})
})
this.series = arr
} else {
console.log('Error while fetching invoice series!')
}
})
.catch(e => {
console.log(e)
})
} else {
invsrs.forEach(function(s) {
arr.push({
value: s.id,
text: s.series + ' / ' + s.increment
})
})
this.series = arr
}
}

这是在 vuex 模块的操作部分中定义的函数:

get_invoice_series({ commit }) {
return get('/api/series/0')
.then(response => {
if (response.data && typeof response.data !== undefined) {
let payload = response.data
commit('SET_INVOICE_SERIES', payload)
} else {
console.log('error', error)
}
})
.catch(error => {
console.log('error', error)
})
},

因此,如您所见,我在操作中返回了来自 axios 的 get 请求。在父级中,我调用了操作和"then"关键字,以便在操作完成后进行一些处理。我也在使用箭头函数,因为我需要父函数中的上下文才能调用它$store。

问题是,即使在检查 getter 以查看状态是否有发票系列并使用get_invoice_series操作获取它们之后,根据我编写的代码判断,内存中仍然没有发票系列。控制台保持登录">获取发票系列时出错!我第一次执行代码和第二次(在信息存在于状态之后(,代码跳过获取发票系列(如预期的那样(。

你能告诉我我做错了什么吗?谢谢!

您的错误来自invsrs第一次为空,第二次为空。

这意味着您的函数get_invoice_series({ commit })是异步的,并且它返回一个承诺。

为了提高可读性,也许您应该独立于return语句进行调用,使用以下async/await表达式:

async get_invoice_series({ commit }) {
const response = await get('/api/series/0')
if (response.data === undefined) return null    
const payload = response.data
commit('SET_INVOICE_SERIES', payload)
return payload
},

然后让您的调用等待此提取处理:

async fetchInvoiceSeries() {
let arr = []
const invsrs = await this.$store.getters['getInvoiceSeries']
// ...

这里纯粹是猜想,让我知道它是否有帮助。

最新更新