Vue中$store.dispatch的Promise未等待异步请求完成是什么原因?
问题根因
- 核心原因:Vuex的
getPatientListaction没有返回Axios异步请求的Promise对象
Vuex的dispatch方法返回值就是对应action的返回值,你当前的action中仅执行了axios.get调用但没有将它返回,导致dispatch返回的是一个无等待逻辑、直接进入resolved状态的空Promise,因此组件中dispatch后的then回调会在接口请求还未返回、mutation还未提交的阶段就提前执行,此时读取patientNotSeenListgetter自然拿到的是未初始化的undefined值。 - 次要隐患:初始化Vuex state时未提前声明
patientSeenList、patientNotSeenList属性
如果你使用的是Vue2版本,直接给state动态新增未提前声明的属性无法触发响应式更新,就算后续mutation完成赋值,组件也监听不到数据变化,无法触发重新渲染。Vue3不存在该限制,但提前声明state属性仍是规范写法。 - 附加语法问题:你当前的action代码中catch分支存在语法错误,字符串后的console.log缺少闭合括号,也可能导致异常逻辑无法正常捕获。
修复方案
- 修改action代码,返回Axios的Promise实例:
actions: { getPatientList({ commit }, date) { console.log(`[In Store::getPatientList, getting patient list...]`); // 新增return,把axios的Promise返回给dispatch return axios .get(constants.API_GETPATIENT_LIST, { params: { // 你的参数逻辑 }, }) .then(({ data }) => { console.log(`Got data is`); console.log(data); let patientSeen = data.results.filter( (checkin) => checkin.consulted == 1 ); let patientNotSeen = data.results.filter( (checkin) => checkin.consulted == 0 ); console.log(`patientSeen is`); console.log(patientSeen); console.log(`patientNotSeen is`); console.log(patientNotSeen); console.log(`[Finished action for Store::getPatientList]`); commit("STORE_PATIENT_LIST", { seen: patientSeen, notseen: patientNotSeen, }); }) .catch((error) => { console.log("In Store::getPatientList,Could not get data from API. Maybe not logged in, or dont have token?") console.log(error); }) }, }
- 补全state的初始化声明:
state: { patientSeenList: [], patientNotSeenList: [] },
修改后dispatch会等待Axios请求完成、mutation提交后再执行then回调,此时读取getter就能拿到正确的患者列表,页面也会正常渲染。
内容的提问来源于stack exchange,提问作者Joel G Mathew
相关产品推荐
相关产品推荐

