我有这段代码,但收到此错误 - “无法在异步函数之外使用关键字 'await'”:
async login() {
try {
this.$validator.validateAll().then((result) => {
if (result) {
this.state = 'LOADING';
this.response = [];
const authResponse = await axios.post('/api/auth/login', this.user);
const auth = authResponse.data;
if (auth.success) {
this.$authLoggedIn(auth);
this.$authRedirectToDefault();
} else {
this.response.push(auth.error);
this.state = 'ERROR';
}
}
});
} catch (error) {
this.state = 'ERROR';
this.response.push(error);
}
},
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?被困在这个问题上几个小时了。
谢谢。
您不需要自己使用 来解开承诺.then,因为您已经处于异步函数中。当您使用.then((result) => {...})该箭头功能时,它不再是异步的。我的建议:
try {
const result = await this.$validator.validateAll()
if (result) {
this.state = 'LOADING';
this.response = [];
const authResponse = await axios.post('/api/auth/login', this.user);
const auth = authResponse.data;
if (auth.success) {
this.$authLoggedIn(auth);
this.$authRedirectToDefault();
} else {
this.response.push(auth.error);
this.state = 'ERROR';
}
}
} catch (error) {
this.state = 'ERROR';
this.response.push(error);
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以通过执行以下操作将箭头函数标记为异步:
this.$validator.validateAll().then(async (result) => {
Run Code Online (Sandbox Code Playgroud)