原因

TypeError: Cannot read property 'setData' of undefined 通常是因为在JavaScript的回调函数中,this 的指向不是你所期望的对象。

  1. 比如说我的这段代码,我在云函数的回调中使用this.setData就报错了。

解决方案不仅仅对云函数有用,对于绝大部分this.setData报错都有用

getGoodDetail(id) {
    const url = `${baseUrl}id`;
    console.log(url);
    //调用云函数
    wx.cloud.callFunction({
      name: 'GET',
      data: {
        url: url,
      },
      success: function (res) {
        var result = JSON.parse(res.result);
        const productData = result.data;
        this.setData({
          product: productData,
        });
      },
      fail: console.error,
    });
  },

在代码中,thissuccess 回调函数中被用于调用 setData 方法,但是在回调函数的上下文中,this 并不指向外部的 getGoodDetail 函数的实例。这是因为在JavaScript中,函数的上下文(即 this 的值)是在函数被调用时确定的,而不是在函数被定义时确定的。

解决方案

  1. 使用箭头函数(推荐)
    箭头函数不会创建自己的 this 上下文,而是继承自它们的父作用域。这意味着你可以在外部函数中使用箭头函数来保持 this 的上下文不变。

    getGoodDetail(id) {
      const url = `${baseUrl}id`;
      wx.cloud.callFunction({
        name: 'GET',
        data: {
          url: url,
        },
        success: (res) => { // 使用箭头函数
          var result = JSON.parse(res.result);
          const productData = result.data;
          this.setData({
            product: productData,
          });
        },
        fail: console.error,
      });
    }
    
  2. 使用变量保存 this 的引用
    在进入 wx.cloud.callFunction 调用之前,你可以创建一个变量(通常命名为 thatself)来存储 this 的当前值,然后在你的回调函数中使用这个变量。

    getGoodDetail(id) {
      const url = `${baseUrl}id`;
      var that = this; // 保存this的引用
      wx.cloud.callFunction({
        name: 'GET',
        data: {
          url: url,
        },
        success: function (res) {
          var result = JSON.parse(res.result);
          const productData = result.data;
          that.setData({ // 使用that代替this
            product: productData,
          });
        },
        fail: console.error,
      });
    }
    

选择其中一种方式修改你的代码,应该就可以解决 TypeError: Cannot read property 'setData' of undefined 这个问题了。

更多推荐