bug(去getS):

This commit is contained in:
zhangjing1
2026-03-17 11:14:42 +08:00
parent dafad06ba1
commit 6ac019fbb9
5 changed files with 29 additions and 72 deletions

View File

@@ -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'
}
}

View File

@@ -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'
// 惰性获取 spxreq 与 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) {

View File

@@ -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()

View File

@@ -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,

View File

@@ -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 {