Vue3中Axios请求更新后Data属性仍为null的问题求助
问题原因
这就是典型的异步操作时序问题:Axios的POST请求是异步执行的,当你在getDates里调用this.getBaseCalendarShifts()后,代码不会等待请求完成,而是直接往下执行let baseCalendarShifts = this.responseBaseCalendarShifts和打印语句——这时候请求还处于pending状态,responseBaseCalendarShifts自然还是初始的空数组。只有当请求成功返回后,then回调里的赋值才会执行,所以那时候打印response.data是正确的。
解决方案
有两种常用的解决方式,可根据代码结构偏好选择:
方案一:用async/await改造(推荐,逻辑更清晰)
把getBaseCalendarShifts改成返回Promise,然后在getDates里用await等待请求完成:
data() { return { dateList: [], year: new Date().getFullYear(), monthNumbers: Array.from(Array(12).keys()), lastDateClicked: null, responseBaseCalendarShifts: [] } }, async getDates() { let dateArray = []; let currentDate = new Date(this.year, 0, 1); // 等待请求完成再继续执行后续代码 await this.getBaseCalendarShifts(); let baseCalendarShifts = this.responseBaseCalendarShifts; console.log(this.responseBaseCalendarShifts) // 现在能拿到正确数据 while (currentDate <= new Date(this.year, 11, 31)) { let dateProperties = { id: `${currentDate.getFullYear()}-${currentDate.getMonth()}-${currentDate.getDate()}`, date: currentDate, year: currentDate.getFullYear(), month: currentDate.getMonth(), day: currentDate.getDate(), dayOfWeek: currentDate.getDay(), active: false }; dateArray.push(dateProperties); currentDate = currentDate.addDays(1); } this.dateList = dateArray; }, getBaseCalendarShifts() { // 返回Axios的Promise对象,让外部可以await return axios.post(this.route, null, { params: { year: this.year } }) .then(response => { this.responseBaseCalendarShifts = response.data; console.log(response.data); }) .catch(function (error) { flash('error', error); }) }
方案二:把依赖异步数据的逻辑放到回调里
如果不想用async/await,可以把getDates里需要用到responseBaseCalendarShifts的代码移到getBaseCalendarShifts的then回调中:
data() { return { dateList: [], year: new Date().getFullYear(), monthNumbers: Array.from(Array(12).keys()), lastDateClicked: null, responseBaseCalendarShifts: [] } }, getDates() { let currentDate = new Date(this.year, 0, 1); this.getBaseCalendarShifts().then(() => { let baseCalendarShifts = this.responseBaseCalendarShifts; console.log(this.responseBaseCalendarShifts) // 能拿到正确数据 let dateArray = []; while (currentDate <= new Date(this.year, 11, 31)) { let dateProperties = { id: `${currentDate.getFullYear()}-${currentDate.getMonth()}-${currentDate.getDate()}`, date: currentDate, year: currentDate.getFullYear(), month: currentDate.getMonth(), day: currentDate.getDate(), dayOfWeek: currentDate.getDay(), active: false }; dateArray.push(dateProperties); currentDate = currentDate.addDays(1); } this.dateList = dateArray; }); }, getBaseCalendarShifts() { return axios.post(this.route, null, { params: { year: this.year } }) .then(response => { this.responseBaseCalendarShifts = response.data; console.log(response.data); }) .catch(function (error) { flash('error', error); }) }
关键提示
- 异步操作(比如Axios请求、定时器)不会阻塞代码执行,必须确保依赖异步结果的逻辑在异步操作完成后再执行。
- 用async/await时,建议给
await包裹try/catch块处理请求错误,避免未捕获的Promise异常。
内容的提问来源于stack exchange,提问作者user5318896
相关产品推荐
相关产品推荐

