微信小程序 报错:this.setData is not a function

Dear 丶 2022-06-10 09:13 327阅读 0赞

微信小程序 报错:this.setData is not a function

在page中定义的代码如下,代码会报错:this.setData is not a function

  1. pasteEncryptedText:function(){
  2. let decryptedPass = this.data.decryptedPassword;
  3. if (decryptedPass == '' ){
  4. wx.showToast({
  5. title: '请先输入解密密码',
  6. mask: true,
  7. success: function (res) {
  8. setTimeout(function () {
  9. wx.hideToast();
  10. }, 4000);
  11. },
  12. });
  13. return;
  14. }else{
  15. wx.getClipboardData({
  16. success: function (res) {
  17. if ( res.data == '' ){
  18. wx.showToast({
  19. title: '剪贴板没有内容',
  20. mask: true,
  21. success: function (res) {
  22. setTimeout(function () {
  23. wx.hideToast();
  24. }, 4000);
  25. },
  26. })
  27. }else{
  28. console.log(decryptedPass);
  29. console.log(res.data);
  30. this.setData({
  31. encryptedTextDecode: res.data,
  32. originalTextDecode: desEncryptedDecrypted.decrypt(res.data, decryptedPass),
  33. });
  34. console.log(this.data.originalTextDecode);
  35. }
  36. }
  37. });
  38. }
  39. }

问题分析:在函数 pasteEncryptedText()里面嵌套调用另一个函数 wx.showToast(),而setData()是在wx.showToast()中调用的,此时this.setData()中的this不是page,而是wx.showToast()这个对象了

解决方法: 在函数pasteEncryptedText()一开始处将this对象保存:let that = this;

  1. pasteEncryptedText:function(){
  2. let decryptedPass = this.data.decryptedPassword;
  3. let that = this;
  4. if (decryptedPass == '' ){
  5. wx.showToast({
  6. title: '请先输入解密密码',
  7. mask: true,
  8. success: function (res) {
  9. setTimeout(function () {
  10. wx.hideToast();
  11. }, 4000);
  12. },
  13. });
  14. return;
  15. }else{
  16. wx.getClipboardData({
  17. success: function (res) {
  18. if ( res.data == '' ){
  19. wx.showToast({
  20. title: '剪贴板没有内容',
  21. mask: true,
  22. success: function (res) {
  23. setTimeout(function () {
  24. wx.hideToast();
  25. }, 4000);
  26. },
  27. })
  28. }else{
  29. console.log(decryptedPass);
  30. console.log(res.data);
  31. that.setData({
  32. encryptedTextDecode: res.data,
  33. originalTextDecode: desEncryptedDecrypted.decrypt(res.data, decryptedPass),
  34. });
  35. console.log(that.data.originalTextDecode);
  36. }
  37. }
  38. });
  39. }
  40. }

发表评论

表情:
评论列表 (有 0 条评论,327人围观)

还没有评论,来说两句吧...

相关阅读