DiscordJS获取实际离线用户status时报cannot read properties of null错误
报错原因
用户真实离线时,member.presence 会返回 null,直接读取null.status就会触发cannot read properties of null (reading 'status')报错。
你之前测试的手动设置为显示离线,属于「用户实际在线但主动将状态可见性设为离线」的场景,此时presence对象存在、status值为offline,所以功能运行正常;只有用户完全离线、没有活跃的在线状态数据时,presence字段才会返回null。
修复方法
访问status属性前先做空值兜底,presence不存在时默认按离线状态处理即可。
支持ES2020可选链语法的环境可以直接这么写:
const statusTypes = { online: '<:online:313956277808005120> Online', idle: '<:away:313956277220802560> Idle', dnd: '<:dnd:313956276893646850> Do Not Disturb', offline: '<:offline:313956277237710868> Offline' }; // embed field { name: 'Status', value: statusTypes[member.presence?.status ?? 'offline'], inline: true },
如果运行环境不支持可选链,用传统三元判断写法也能实现同样效果:
// 先取到兜底后的状态值 const currentStatus = member.presence ? member.presence.status : 'offline'; // embed字段部分 { name: 'Status', value: statusTypes[currentStatus], inline: true },
内容的提问来源于stack exchange,提问作者user16486451
相关产品推荐
相关产品推荐

