最近使用发现使用lodash throttle/debounce 报错:
MiniProgramError
undefined is not an object (evaluating 'tr.Z.Date.now')
TypeError: undefined is not an object (evaluating 'tr.Z.Date.now')
debug后发现无法访问`global`对象啦,一旦访问就报错!debug代码如下:
// attempt to access global:
function attempt(fn, ...args){
try {
return fn(...args)
} catch (e) {
console.error(e)
}
}
attempt(() => {
console.log('access global')
console.log(global)
})
attempt(() => {
console.log('access globalThis')
console.log(globalThis)
})
attempt(() => {
console.log('access self')
console.log(self)
})
attempt(() => {
console.log('get global in lodash way')
const freeGlobal = typeof global == 'object' && global && global.Object === Object && global
const freeSelf = typeof self == 'object' && self && self.Object === Object && self
const root = freeGlobal || freeSelf || Function('return this')()
console.log({ root })
})
报错信息如下:
access global
<TypeError: no access>TypeError: no access
at FAe
(https://lib/WAServiceMainContext.is:1:1584618)
at https://lib/WAServiceMainContext.is:1:1587463
...
微信版本:8.0.38
基础库版本:2.30.4
你解决了吗?
可以尝试在 app.js 顶部执行下面的代码,该代码的作用是将 global 缺少的数据补充一部分,根本原因就是lodash中访问到的 global 对象是小程序提供的,一般情况下是在小程序中用来全局共享数据的
// 补全lodash中用到的变量 Object.assign(global, { Array, Date, Error, Function, Math, Object, RegExp, String, TypeError, setTimeout, setInterval, });