开发中遇到微信小程序“this.setData is not a function”错误,具体错误内容如下所示:
VM10092:1 thirdScriptError
this.setData is not a function;at pages/index/index onReachBottom function;at setTimeout callback function
TypeError: this.setData is not a function
at Function.<anonymous> (http://127.0.0.1:36316/appservice/pages/index/index.js:67:12)
at http://127.0.0.1:36316/appservice/__dev__/WAService.js:1:100596
at http://127.0.0.1:36316/appservice/__dev__/WAService.js:1:89364
错误分析:
遇到这样的错误,一般在主函数上直接使用“this.setData”不会有上述的错误,但是在主函数下面的子函数里面使用,例如“wx.request”或setTimeout,setinterval等,都会出现错误,小编的错误代码如下:
/** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { this.setData({ isHideLoadMore: "block" }) timer = setTimeout(function(){ this.setData({ isHideLoadMore: "none" }) },3000) },
错误解决:
我们只需要将里面的“this”改成“that”来代替,就不会出现这样的错误了,如下所示即可:
/** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { var that = this; this.setData({ isHideLoadMore: "block" }) timer = setTimeout(function(){ that.setData({ isHideLoadMore: "none" }) },3000) },