前端:this指针问题,uniapp出现Cannot read property ‘dispatch‘ of undefine

文章讨论了在使用微信登录功能时,由于uniapp的微信API调用导致的this指向问题,影响了Vue实例的访问。作者提供了将`that`提前赋值为`this`的解决方法,确保在回调函数中能正确调用Vuexstore中的方法。
摘要由CSDN通过智能技术生成

其实这个问题不止在uniapp身上出现,很多用vue语法的都可能会出现问题,关键是在于对指针的了解。

业务场景:微信登录场景:需要调用微信的各类api。以下是代码初始展示。

 getUserProfile(){

let code = '';

var that = this;

uni.showLoading({ title: '正在登录中' });

//调用微信获取code

uni.login({ provider:'weixin', success: (logRes) => { // console.log(logRes.code) code = logRes.code } });

uni.getUserProfile({ lang: 'zh_CN', desc: '用于核对员工注册资料信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写

success(user)

const data = { code:code, encryptedIv:user.iv, encryptedData:user.encryptedData }

// 登录用户信息

wxLogin(data).then(res => { 

if(res.code===201){

 }else if (res.code===200)

{ this.$store.dispatch('WxLogin', res.data.token).then(() => {

this.loginSuccess() })

}else{ return null; } }) },

fail(error){ console.log("error....",error) } })

uni.hideLoading();

主要的报错地方在以上标红地方,主要是调用vuex的store里面的方法报的错误,使用vuex并没有错误,错误的是this指向问题。出现错误的原因是我用了微信uniapp提供的api,uni.login和uni.getIserProfile两个方法,这会导致指针已经不再指向vue实例,而是指向回调函数本身。这会导致在回调函数中无法直接访问Vue实例的属性和方法。

解决方法,先上改动的代码

 getUserProfile(){

      uni.showLoading({

          title: '正在登录中'

      });

          let code = '';

          var that = this;

          //调用微信获取code

          uni.login({

              provider:'weixin',

              success: (logRes) => {

                  code = logRes.code

              }

          });

          uni.getUserProfile({

              lang: 'zh_CN',

              desc: '用于核对员工注册资料信息',

              success(user) {

                  const data = {

                      code:code,

                      encryptedIv:user.iv,

                      encryptedData:user.encryptedData

                  }

                  wxLogin(data).then(res => {

                      console.log(res)

                      if(res.code===201){

                      }else if (res.code===200){

                          that.$store.dispatch('WxLogin', res.data.token).then(() => {

                              that.loginSuccess()

                          })

                      }else{

                          return null;

                      }

                  })

              },

              fail(error){

                  console.log("error....",error)

              }

          })

          uni.hideLoading();

      },

其实解决方法很简单,只要在方法开始之前,先把指向存下来,var that = this;使用var变量提升,防止有其他bug的出现,存好了指向后,后续只要用tha.dispatch即可调用到vuex里的内容。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值