this.setData is not a function;at pages/index/index onLoad function;at api request success callback function TypeError: this.setData is not a function

微信小程序中 ,API请求数据显示 this.setData is not a function

原因:this指向问题

解决:在函数中加入var that = this;使用that.setData()代码如下

 1 onLoad: function (options) {
 2     var that = this;
 3     // 发送异步请求,获取轮播图数据
 4     wx.request({
 5       url: 'http://localhost:3000/getlunbotu',  // 请求路径
 6       data: '',  // 发送数据给后台
 7       header: {}, // 请求头
 8       method: 'GET', // 请求方式
 9       dataType: 'json', // 返回值类型,默认json
10       responseType: 'text', // 文本类型
11       success: function (res) { // 成功后
12         // console.log(res.data)
13         that.setData({
14           swiperList: res.data
15         })
16       }, 
17       fail: function(res) {}, // 失败后
18       complete: function(res) {}, // 成功或失败后都会执行
19     })
20   },

1、如果函数作为对象的方法调用,this指向的是这个上级对象,即调用方法的对象。
2、如果是构造函数中的this,则this指向新创建的对象本身。

原文地址:https://www.cnblogs.com/zhaohui-116/p/12506383.html