Vue3异步方法访问data字段报TypeError错误如何解决?
问题原因
你代码的报错核心是then()回调中使用的普通匿名函数存在this指向偏移问题。普通函数的this会在调用时动态绑定,异步回调触发时已经脱离了组件方法的执行上下文,此时this值为undefined,自然无法访问挂载在实例上的nameCity字段。
解决方案
方案1:使用箭头函数替换普通回调函数
箭头函数不会创建自身的this,会继承外层作用域的this指向,此处外层findCity方法的this指向组件实例,因此回调内可以直接访问到正确的实例:
export default { data() { return { nameCity: '', } }, methods: { findCity(event){ event.preventDefault() // 把普通function改为箭头函数 findCityCust().then(response => { console.log(response) this.nameCity = response; }) }, }, }
方案2:提前保存外层this指向
在异步逻辑执行前,先把组件实例的this存到临时变量中,回调内直接访问临时变量即可:
export default { data() { return { nameCity: '', } }, methods: { findCity(event){ event.preventDefault() // 提前保存实例指向 const vm = this findCityCust().then(function(response) { console.log(response) vm.nameCity = response; }) }, }, }
方案3:用async/await改写异步逻辑
async/await是更简洁的异步写法,同时不会产生额外的函数作用域,天然继承外层this:
export default { data() { return { nameCity: '', } }, methods: { // 给方法加async修饰 async findCity(event){ event.preventDefault() const response = await findCityCust() console.log(response) this.nameCity = response; }, }, }
Vue3
相关产品推荐
相关产品推荐

