
function request(requestMapping, data, requestWay, contentType) { wx.showLoading({ title: '请稍后', }) return new Promise(function(resolve, reject) { console.log('请求中。。。。。') wx.request({ url: '自己的服务器地址' + requestMapping, data: data, header: { 'content-type': contentType // 默认值 }, timeout: 3000, method: requestWay, success(res) { //console.log(res) if (res.data.success == false || res.data.statusCode == 404) { reject(res) } else { resolve(res) } }, fail: (e) => { wx.showToast({ title: '连接失败', icon: 'none' })}, complete: () => { wx.hideLoading() } }) }) } //获取 openid function getOpenId(app, that){ return new Promise(function (resolve, reject) { wx.login({ success: function (yes) { // 发送 res.code 到后台换取 openId, sessionKey, unionId var requestMapping = '/testopenid' var data = { code: yes.code } var requestWay = 'GET' var cOntentType= 'application/json' var p =request(requestMapping, data, requestWay, contentType) p.then(res => { //console.log(res) 做一些后续操作 app.globalData.openId = res.data; resolve(res) }).catch(e => { reject(e) }) }, fail(e) { console.log(e) } }) }) } getOpenId(getApp(),this);
1 horseInBlack 2022-10-02 13:52:24 +08:00 从报错信息来看应该是 你在一个 undefined 的变量上读取了 globalData 属性,所以其实是传进去的 app 就是 undefined 我没写过原生微信小程序,我只从我看到的地方猜测一下可能的问题 1.直接在外面打印一下这个 app 看看对不对,再看看 app.globalData 对不对 2.我看到你定义了一个 getOpenId 函数,然后传入了 getApp() 的回调 和 当前 this 2.1 但是你在成功的回调方法里写了 success: function (yes) { 可以试着用箭头函数重写,而不是用 that(况且你贴的这些代码好像也没用到 that) success:(res)=>{} 2.2 也可以不封装这么复杂,直接在函数内部调用 getApp().globalData 去获取、设置 globalData ,先实现功能再考虑封装优化 |
2 Aixtuz 2022-10-02 15:12:29 +08:00 确认一下 getApp() 确实存在么? 太久没写有点记不太清楚了,模糊记得以前遇到过小程序中的启动过程的某些顺序和预想的并不一样。 一般去小程序的社区搜一搜,其他人遇到的情况,比较容易有所发现。 例如: https://developers.weixin.qq.com/community/search?query=getApp%28%29&page=1 |
3 Aixtuz 2022-10-02 15:18:10 +08:00 我以前遇到类似的问题是这个原因导致的: index.js 页和 app.js 是异步执行的。 不确定你的情况是否一样,贴一下以便你留意到这一点吧~ |
4 autoname OP @Aixtuz @horseInBlack 非常感谢大佬们的回复,已经好了,可能和网上说的一样,this 指向别的地方了, 赋值在 that 上面 中转下就好了,刚接触小程序,还纳闷怎么要多此一举(别人的项目),好多方法里面都有这 that 中转 |