You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3访问data属性报Cannot read properties of undefined (reading 'results')如何解决

错误产生原因

该错误由普通函数的this指向规则导致:

  • methods中定义的getData方法的this默认绑定Vue组件实例,但你在fetch的then回调中使用了普通function声明回调函数,普通函数的this指向由调用方决定,then执行回调时没有绑定外层组件实例,在Vue3默认的严格模式下该this值为undefined,因此访问this.results抛出类型错误。
解决方案

下面是4种常见的可行解法,推荐优先使用前两种:

解法1:使用箭头函数作为回调(最常用)

箭头函数不会创建自己的this,会继承外层作用域的this值,直接替换then中的普通函数即可:

methods: {
  getData() {
    fetch("http://rb.test/api/posts/all")
      .then((response) => {
        if (response.ok) {
          return response.json();
        }
      })
      .then((data) => {
        this.results = data;
        console.log(this.results);
      });
  },
}

解法2:使用async/await重写异步逻辑

异步逻辑用async/await改写后更易读,且不需要额外处理this指向:

methods: {
  async getData() {
    try {
      const response = await fetch("http://rb.test/api/posts/all")
      if (response.ok) {
        const data = await response.json()
        this.results = data
        console.log(this.results)
      }
    } catch (err) {
      console.error('请求失败:', err)
    }
  },
}

解法3:提前缓存外层this

在getData开头提前把组件实例的this缓存到变量中,回调中直接访问该变量即可:

methods: {
  getData() {
    const vm = this // 缓存组件实例
    fetch("http://rb.test/api/posts/all")
      .then(function (response) {
        if (response.ok) {
          return response.json();
        }
      })
      .then(function (data) {
        vm.results = data;
        console.log(vm.results);
      });
  },
}

解法4:用bind绑定this

给每个then的普通函数绑定外层this指向组件实例:

methods: {
  getData() {
    fetch("http://rb.test/api/posts/all")
      .then(function (response) {
        if (response.ok) {
          return response.json();
        }
      }.bind(this))
      .then(function (data) {
        this.results = data;
        console.log(this.results);
      }.bind(this));
  },
}

内容的提问来源于stack exchange,提问作者ktaro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 21:18:03