Vue.js中fetch API请求与.then()函数异常,控制台返回空数组
问题分析与修复方案
你遇到的问题是异步执行顺序错误导致的——checkSpeciality()在API请求还没完成、this.specialityTest还没被赋值的时候就提前执行了,所以控制台输出空数组。
问题出在哪里?
看这段代码:
.then(result => this.specialityTest = result).then(this.checkSpeciality())
第二个then里的this.checkSpeciality()是立即调用的,而不是等待前一个Promise(也就是API请求完成、this.specialityTest赋值完成)之后再执行。这就导致checkSpeciality跑在了赋值操作的前面,自然拿不到数据。
修复方法(两种可选)
方法1:传递函数引用给then
去掉checkSpeciality()的括号,把函数本身作为回调传给then,这样它会在前面的Promise完成后再执行:
fetchSpecialityArray(){ this.$http.get('http://127.0.0.1:8000/api/speciality') .then(response => response.json()) .then(result => { this.specialityTest = result; }) .then(this.checkSpeciality); // 这里不加括号 }
方法2:直接在赋值的回调里调用checkSpeciality
如果逻辑比较简单,也可以把checkSpeciality的调用直接放到第二个then的回调里,这样更直观:
fetchSpecialityArray(){ this.$http.get('http://127.0.0.1:8000/api/speciality') .then(response => response.json()) .then(result => { this.specialityTest = result; this.checkSpeciality(); // 赋值完成后立即调用 }) }
额外提醒
如果你的checkSpeciality里用到了this,要确保它的上下文正确。如果是用方法1的写法,可能需要用bind绑定上下文,或者改成箭头函数:
.then(() => this.checkSpeciality())
这样能保证checkSpeciality里的this指向当前组件实例。
内容的提问来源于stack exchange,提问作者gileneusz
相关产品推荐
相关产品推荐

