不能在 VUEJS 中的异步函数之外使用关键字'await'



当我试图在异步函数Can not use keyword 'await' outside an async function之外等待时,我遇到了这个错误,我想知道应该使用哪种方法来解决这个问题?提前谢谢。

这是我的代码:

async addCoursToClassYear() {
setTimeout(() => {
this.loading = false;
await this.$store.dispatch("academicYear/addCoursToClassYear", {
...this.form,
...this.singleYear
})
.then(() => {
this.handleSuccess();
this.closeModal();
})
.catch(error => {
if (error.response.status === 422) {
this.serverValidation.setMessages(error.response.data.errors);
} else {
this.handleError(error);
}
});
})
},

您正在setTimeout中使用await。因此,您需要使异步setTimeout函数

async addCoursToClassYear() {
setTimeout(async() => {
this.loading = false;
await this.$store.dispatch("academicYear/addCoursToClassYear", {
...this.form,
...this.singleYear
})
.then(() => {
this.handleSuccess();
this.closeModal();
})
.catch(error => {
if (error.response.status === 422) {
this.serverValidation.setMessages(error.response.data.errors);
} else {
this.handleError(error);
}
});
})
},

我更改了

setTimeout(((=>{

setTimeout(async((=>{

这里,只将async放在您使用await的函数中。

async addCoursToClassYear() {
setTimeout(async () => {
this.loading = false;
await this.$store.dispatch("academicYear/addCoursToClassYear", {
...this.form,
...this.singleYear
})
.then(() => {
this.handleSuccess();
this.closeModal();
})
.catch(error => {
if (error.response.status === 422) {
this.serverValidation.setMessages(error.response.data.errors);
} else {
this.handleError(error);
}
});
})
},

最新更新