uni-app 本地调试redis 报 Cannot read properties of undefined (reading 'sigBytes')
uni-app 本地调试redis 报 Cannot read properties of undefined (reading ‘sigBytes’)
产品分类:
uniCloud/支付宝小程序云
示例代码:
const redis = uniCloud.redis()
module.exports = {
_before: function () { // 通用预处理器
},
/**
* 更新puchClientId到redis缓存
* @param {string} param 参数1描述
* @returns {object} 返回值描述
*/
async save_push_client_id_to_redis(params) {
let test = await redis.set("123","456")
console.log(test)
let redisRes = await redis.get('123')
console.log(redisRes)
// 返回结果
return {
errCode: 0,
errMsg: 'success'
}
},
操作步骤:
- 建立一个云对象,然后输入上面代码示例
预期结果:
- 应该跳出正常结果
实际结果:
- hbuilderx显示如下错误
23:35:37.853 [本地调试]TypeError: Cannot read properties of undefined (reading ‘sigBytes’)
bug描述:
开通了redis服务,在云对象中尝试了最简单的redis数据存储和读取服务,但一直报Cannot read properties of undefined (reading ‘sigBytes’) ,但是,如果我把云对象的代码上传部署,然后使用连接云端云函数的方式进行调试,查看网站上的函数运行日志,又是正常的,hbuilderx这边本地调试就不正常
hbuilderx运行环境 maxos 10.14.5 版本:3.99
这个在小程序云里必现,官方能解决吗
回复 q***@qq.com: 先不用小程序云了 这种问题说实话有点离谱
在 uni-app 中调试 Redis 时遇到 Cannot read properties of undefined (reading 'sigBytes')
错误,通常是因为在代码中尝试访问一个未定义的对象的属性。具体到 sigBytes
,这可能是与加密或哈希相关的库(如 crypto-js
)中的属性。
以下是一些可能的原因和解决方法:
1. 检查 Redis 客户端库的初始化
确保你正确初始化了 Redis 客户端。如果 Redis 客户端未正确初始化,可能会导致后续操作失败。
const redis = require('redis');
const client = redis.createClient();
client.on('error', (err) => {
console.error('Redis error:', err);
});
2. 检查依赖库的版本
如果你使用了 crypto-js
或其他加密库,确保它们的版本是兼容的。有时,库的版本更新可能会导致 API 变化,从而引发错误。
npm install crypto-js[@latest](/user/latest)
3. 检查代码中的变量
确保你在访问 sigBytes
之前,相关的变量已经被正确赋值。例如:
const CryptoJS = require('crypto-js');
const hash = CryptoJS.SHA256('message');
console.log(hash.sigBytes); // 确保 hash 对象存在
如果 hash
是 undefined
或 null
,那么访问 hash.sigBytes
就会抛出错误。
4. 调试和日志
在代码中添加调试信息,检查相关变量的值。例如:
console.log('Hash object:', hash);
if (hash) {
console.log('sigBytes:', hash.sigBytes);
} else {
console.error('Hash is undefined or null');
}
5. 检查异步操作
如果你在异步操作中访问 sigBytes
,确保在访问之前异步操作已经完成。例如:
async function computeHash() {
const hash = await CryptoJS.SHA256('message');
console.log(hash.sigBytes);
}
computeHash();
6. 检查环境兼容性
uni-app 是一个跨平台框架,某些库可能在特定的平台上表现不同。确保你使用的库在目标平台上兼容。
7. 检查代码逻辑
检查代码逻辑,确保没有遗漏的步骤或错误的逻辑导致变量未定义。
8. 更新依赖
有时,依赖库的旧版本可能会导致问题。尝试更新所有依赖库到最新版本:
npm update
9. 检查 Redis 连接
如果问题与 Redis 相关,确保 Redis 服务器正在运行,并且客户端能够成功连接到服务器。
client.ping((err, reply) => {
if (err) {
console.error('Redis connection error:', err);
} else {
console.log('Redis is connected:', reply);
}
});