From 6ac019fbb90db0bc79f4a7a1539858c1d95e093f Mon Sep 17 00:00:00 2001 From: zhangjing1 Date: Tue, 17 Mar 2026 11:14:42 +0800 Subject: [PATCH] =?UTF-8?q?bug(=E5=8E=BBgetS):?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/api/guide.js | 13 ++----------- src/api/req.js | 27 +++++++++------------------ src/spx/index.js | 29 ++++++++++------------------- src/utils/entryLaunch.js | 16 ++++------------ src/utils/index.js | 16 ++++------------ 5 files changed, 29 insertions(+), 72 deletions(-) diff --git a/src/api/guide.js b/src/api/guide.js index f519ac16b..543b0b1eb 100644 --- a/src/api/guide.js +++ b/src/api/guide.js @@ -1,24 +1,15 @@ /** * Copyright © ShopeX (http://www.shopex.cn). All rights reserved. * See LICENSE file for license details. - * 公众号/服务号冷启动时不在顶层 import S,否则会 ReferenceError: Can't find variable: S */ +import S from '@/spx' import { transformPlatformUrl } from '@/utils/platform' import req from './req' -function getS() { - return ( - (typeof global !== 'undefined' && global.__SPX__) || - (typeof globalThis !== 'undefined' && globalThis.__SPX__) || - null - ) -} - function createHead() { - const s = getS() return { header: { - 'x-wxapp-session': (s && s.getAuthToken && s.getAuthToken()) || '', + 'x-wxapp-session': (S && S.getAuthToken()) || '', 'salesperson-type': 'shopping_guide' } } diff --git a/src/api/req.js b/src/api/req.js index ec8930b1c..6002f909d 100644 --- a/src/api/req.js +++ b/src/api/req.js @@ -4,7 +4,7 @@ */ import Taro, { getCurrentInstance } from '@tarojs/taro' import qs from 'qs' -import spxInstance from '@/spx' +import S from '@/spx' import { isAlipay, isWeixin, @@ -17,15 +17,6 @@ import { import log from '@/utils/log' import { HTTP_STATUS } from './consts' -// 惰性获取 spx:req 与 spx 存在循环依赖(spx→api→req→spx),加载时 spxInstance 可能尚未就绪 -function getS() { - return ( - (typeof global !== 'undefined' && global.__SPX__) || - (typeof globalThis !== 'undefined' && globalThis.__SPX__) || - spxInstance - ) -} - function addQuery(url, query) { return url + (url.indexOf('?') >= 0 ? '&' : '?') + query } @@ -153,7 +144,7 @@ class API { handleLogout() { this.requestQueue.destroy() this.isRefreshingToken = false - getS().logout() + S.logout() setTimeout(() => { console.log(getCurrentInstance()?.router) const { path, params } = getCurrentInstance()?.router @@ -186,21 +177,21 @@ class API { if (company_id) { query['company_id'] = company_id } - const lang = Taro.getStorageSync('lang') || process.env.APP_DEFAULT_LANGUAGE || process.env.APP_COUNTRY_CODE + const lang = Taro.getStorageSync('lang') + if (lang) { const langMap = { zhcn: 'zh-CN', en: 'en-CN', zhtw: 'zh-TW', ar: 'ar-SA' } - if (langMap[lang]) { - query['country_code'] = langMap[lang] + query['country_code'] = langMap[lang || process.env.APP_COUNTRY_CODE] } if (!methodIsGet) { header['content-type'] = header['content-type'] || 'application/x-www-form-urlencoded' } - const token = getS().getAuthToken() + const token = S.getAuthToken() if (token) { header['Authorization'] = `Bearer ${token}` } @@ -279,7 +270,7 @@ class API { async refreshToken() { this.isRefreshingToken = true - const token = getS().getAuthToken() + const token = S.getAuthToken() console.log('refreshToken', 66) try { await this.makeReq( @@ -299,7 +290,7 @@ class API { } const newToken = res.header.Authorization.split(' ')[1] - getS().setAuthToken(newToken) + S.setAuthToken(newToken) } ) } catch (e) { @@ -337,7 +328,7 @@ class API { if ( res.statusCode === HTTP_STATUS.UNAUTHORIZED && (res.data.data && res.data.data.code) === HTTP_STATUS.TOKEN_NEEDS_REFRESH && - getS().getAuthToken() + S.getAuthToken() ) { // token失效时重造请求,并刷新token if (!this.isRefreshingToken) { diff --git a/src/spx/index.js b/src/spx/index.js index 1d750e7a7..ca5a32b25 100644 --- a/src/spx/index.js +++ b/src/spx/index.js @@ -3,13 +3,12 @@ * See LICENSE file for license details. */ import Taro, { getCurrentInstance } from '@tarojs/taro' +import api from '@/api' import { isWeixin, isAlipay, log, isGoodsShelves, showToast, isMerchantModule } from '@/utils' import { SG_TOKEN, SG_USER_INFO, MERCHANT_TOKEN } from '@/consts/localstorage' import dayjs from 'dayjs' import qs from 'qs' import configStore from '@/store' -// 按需加载 api,避免 spx→api→req→spx 循环依赖导致冷启动时 S 为 undefined -const getApi = () => require('@/api').default const { store } = configStore() @@ -137,7 +136,7 @@ export class Spx { desc: '用于完善会员资料', success: async (data) => { const { userInfo } = data - await getApi().member.updateMemberInfo({ + await api.member.updateMemberInfo({ username: userInfo.nickName, avatar: userInfo.avatarUrl }) @@ -156,7 +155,7 @@ export class Spx { // 获取会员信息 async getMemberInfo() { - const userInfo = await getApi().member.memberInfo() + const userInfo = await api.member.memberInfo() store.dispatch({ type: 'user/updateUserInfo', payload: userInfo @@ -206,7 +205,7 @@ export class Spx { async login(ctx, isRedirect = false) { let code, token if (isWeixin) { - let { update_time } = await getApi().wx.getPrivacyTime() + let { update_time } = await api.wx.getPrivacyTime() let privacy_time = Taro.getStorageSync('policy_updatetime') if (!String(privacy_time) || privacy_time != update_time) { return true @@ -215,7 +214,7 @@ export class Spx { const resLogin = (await Taro.login()) || {} code = resLogin.code try { - const tokenLogin = (await getApi().wx.login({ code })) || {} + const tokenLogin = (await api.wx.login({ code })) || {} token = tokenLogin.token } catch (e) { return true @@ -223,7 +222,7 @@ export class Spx { } else if (isAlipay) { const authLogin = await my.getAuthCode({ scopes: ['auth_base'] }) code = authLogin.authCode - const tokenLogin = await getApi().alipay.login({ code }) + const tokenLogin = await api.alipay.login({ code }) token = tokenLogin.token } if (token) { @@ -248,14 +247,14 @@ export class Spx { async loginQW(ctx) { console.log('[loginQW] 企微登录 执行') let { code } = await this.getQyLoginCode() - const QwUserInfo = await getApi().user.getQwUserInfo({ + const QwUserInfo = await api.user.getQwUserInfo({ appname: `${APP_NAME}`, code }) let { salesperson_id, distributor_id, session3rd } = QwUserInfo this.setAuthToken(session3rd) //查询当前导购门店信息是否有效 - const { status } = await getApi().guide.is_valid({ + const { status } = await api.guide.is_valid({ salesperson_id, distributor_id }) @@ -296,7 +295,7 @@ export class Spx { let uvstamp = Taro.getStorageSync('userVisitTime') let today = formatDateTime(new Date()) if (!uvstamp || (uvstamp && new Date(today).getTime() > uvstamp)) { - getApi().user.getuservisit() + api.user.getuservisit() uvstamp = new Date(today).getTime() + 5 * 60 * 1000 Taro.setStorageSync('userVisitTime', uvstamp) } @@ -342,12 +341,4 @@ export class Spx { } } -const instance = new Spx() -// 冷启动从公众号直接打开分包页时,主包未先执行可能导致 import S 未就绪,挂到全局供 req 等使用 -if (typeof global !== 'undefined') { - global.__SPX__ = instance -} -if (typeof globalThis !== 'undefined') { - globalThis.__SPX__ = instance -} -export default instance +export default new Spx() diff --git a/src/utils/entryLaunch.js b/src/utils/entryLaunch.js index 807406f9b..666e1dcfd 100644 --- a/src/utils/entryLaunch.js +++ b/src/utils/entryLaunch.js @@ -12,15 +12,7 @@ import _isEqual from 'lodash/isEqual' import { SG_ROUTER_PARAMS, SG_GUIDE_PARAMS } from '@/consts/localstorage' import MapLoader from '@/utils/lbs' - -// 惰性获取 spx,避免服务号冷启动时 S 未就绪(与 utils 中 getS 逻辑一致,不能从 utils 引入防循环依赖) -function getS() { - return ( - (typeof global !== 'undefined' && global.__SPX__) || - (typeof globalThis !== 'undefined' && globalThis.__SPX__) || - require('@/spx').default - ) -} +import S from '@/spx' const $instance = getCurrentInstance() || {} const { store } = configStore() @@ -208,7 +200,7 @@ class EntryLaunch { lng: res.longitude, lat: res.latitude }) - getS().set('currentLocation', { + S.set('currentLocation', { lng: res.longitude, lat: res.latitude }) @@ -467,7 +459,7 @@ class EntryLaunch { * 导购UV统计 */ async postGuideUV() { - if (!getS().getAuthToken()) return + if (!S.getAuthToken()) return const { gu } = Taro.getStorageSync(SG_GUIDE_PARAMS) || {} if (gu) { const [work_userid] = gu.split('_') @@ -512,7 +504,7 @@ class EntryLaunch { // gu_user_id: 欢迎语上带过来的员工编号, 同work_user_id const { gu, subtask_id, item_id, dtid, smid, gu_user_id, id } = Taro.getStorageSync(SG_GUIDE_PARAMS) || {} - if (gu && getS().getAuthToken()) { + if (gu && S.getAuthToken()) { const [employee_number, shop_code] = gu.split('_') const _params = { employee_number, diff --git a/src/utils/index.js b/src/utils/index.js index 8cf4448f9..8c57839d6 100644 --- a/src/utils/index.js +++ b/src/utils/index.js @@ -10,6 +10,7 @@ import copy from 'copy-to-clipboard' import { STATUS_TYPES_MAP, SG_ROUTER_PARAMS } from '@/consts' import api from '@/api' import configStore from '@/store' +import S from '@/spx' import _get from 'lodash/get' import _findKey from 'lodash/findKey' import _pickBy from 'lodash/pickBy' @@ -29,15 +30,6 @@ import linkPage from './linkPage' const { store } = configStore() -// 惰性获取 spx,避免服务号冷启动打开 custom-page 等页时 utils→spx 循环依赖导致 S 未就绪 -function getS() { - return ( - (typeof global !== 'undefined' && global.__SPX__) || - (typeof globalThis !== 'undefined' && globalThis.__SPX__) || - require('@/spx').default - ) -} - const isPrimitiveType = (val, type) => Object.prototype.toString.call(val) === type export function isFunction(val) { @@ -292,7 +284,7 @@ export function copyText(text, msg = '内容已复制') { return } if (copy(text)) { - getS().toast(msg) + S.toast(msg) resolve(text) } else { reject() @@ -532,7 +524,7 @@ export async function buriedPoint(data) { } api.wx.taskReportData(newData) } - if (data.event_type && getS().getAuthToken() && employee_number) { + if (data.event_type && S.getAuthToken() && employee_number) { const { userId } = Taro.getStorageSync('userinfo') api.wx.interactiveReportData({ event_id: employee_number, @@ -917,7 +909,7 @@ export function buildSharePath(from_scene, params = {}) { const getMobAppExtraData = () => { const store = configStore() - const token = getS().getAuthToken() + const token = S.getAuthToken() const userInfo = token ? tokenParse(token) : {} const aioucd = userInfo?.user_card_code return {