欢迎您光临自学哈网,只为分享网络知识教程,供大家学习参考!

「自学哈网」微信小程序报错:TypeError: Cannot read property ‘setData’ of undefined解决方法

作者 : 自学哈 本文共1714个字,预计阅读时间需要5分钟 2022-11-5 共156人阅读
也想出现在这里? 联系我们

在完成微信小程序的一个功能时,偶然间报了一个错误。
错误信息是:TypeError: Cannot read property ‘setData’ of undefined。

出错代码

每当我执行homework这个函数时,我发送一个request请求,将获取的数据存导本地的数组中。故我在sucess:function(res){}中使用了this.setData({})。

  homework: function () {
    if (this.data.homeworkpageFlag == false) {
      console.log(this)
      this.setData({
        homeworkpageFlag: true,
        saypageFlag: false,
        exampageFlag: false,
      })
    }
    wx.request({
      url: '某url hhhhh',
      data: {
        student_id: '某学号',
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        console.log(res.data)
        this.setData({
          homeworkNoCompleteList: res.data.data.homeworkNoCompleteList
        })
      }
    })

  },


理想很美好,但是每次执行就会报上面的错误。

解决方案

  1. var that = this;
  2. ES6的箭头函数

方案一、var that = this;

添加 var that = this;并把sucess中的this.setData改成that.setData

homework: function () {
    if (this.data.homeworkpageFlag == false) {
      console.log(this)
      this.setData({
        homeworkpageFlag: true,
        saypageFlag: false,
        exampageFlag: false,
      })
    }
    //添加var that = this
    var that = this;
    wx.request({
      url: 'https://fanzaixuexi.applinzi.com/public/index.php/index/GetInformation/get_all_assignment',
      data: {
        student_id: '某学号',
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        console.log(res.data)
        //改成了that.setData
        that.setData({
          homeworkNoCompleteList: res.data.data.homeworkNoCompleteList
        })
      }
    })
  },


成功解决问题。

方案二、ES6箭头函数;

  homework: function () {
    if (this.data.homeworkpageFlag == false) {
      console.log(this)
      this.setData({
        homeworkpageFlag: true,
        saypageFlag: false,
        exampageFlag: false,
      })
    }
    wx.request({
      url: '某url',
      data: {
        student_id: '某id',
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: (res)=> {
        console.log(res.data)
        // var that = this;
        this.setData({
           // 我要获取的数据
        })
        console.log(this.data.homeworkYesCompleteList.length)
      }
    })

  },

把 success:function(res){}改成 success:(res)=>{}
就可以大大方方地使用 this.setData了

本站声明:
本站所有资源来源于网络,分享目的仅供大家学习和交流!如若本站内容侵犯了原著者的合法权益,可联系邮箱976157886@qq.com进行删除。
自学哈专注于免费提供最新的分享知识、网络教程、网络技术的资源分享平台,好资源不私藏,大家一起分享!

自学哈网 » 「自学哈网」微信小程序报错:TypeError: Cannot read property ‘setData’ of undefined解决方法
也想出现在这里? 联系我们
© 2022 Theme by - 自学哈网 & WordPress Theme. All rights reserved 浙ICP备2022016594号