升级Discord.js v14遇TypeError:无法读取null的status属性
升级Discord.js v14后出现TypeError错误
错误信息
TypeError: Cannot read properties of null (reading 'status')
报错代码片段
setInterval(function() { let today = new Date(); time = fancyTime(today); for (let i = 0; i < list.length; i++) { if (!(list[i].presence.status == "offline")) { // 如果用户不在线,更新数组为绿色圆圈并标记他们尚未离线 if (list[i].presence.status == "idle") { timeList[i] = ":orange_circle: " + time; } else if (list[i].presence.status == "dnd") { timeList[i] = ":red_circle: " + time; } else { timeList[i] = ":green_circle: " + time; } firstOffline[i] = 1; } else if ((list[i].presence.status == "offline") && (firstOffline[i] == 1)) { // 如果用户离线且是第一次离线,更新数组为当前时间并标记首次离线 timeList[i] = ":white_circle: " + time; firstOffline[i] = 0; } } // 将值备份到文本文件 fs.writeFile("timeListBackup.txt", timeList, (err) => {}); fs.writeFile("firstOfflineBackup.txt", firstOffline, (err) => {}); }, 1000)
问题原因与解决方案
在Discord.js v14中,list[i].presence返回null是导致报错的核心原因,主要由两点变化引发:
- 网关意图权限收紧:v14要求必须主动声明
GuildPresences和GuildMembers意图,才能获取用户在线状态数据,否则presence会为null。 - 缓存机制调整:v14对用户缓存的处理更严格,若目标用户不在机器人缓存池中,
presence同样会返回null。
具体修复步骤
- 启用必要网关意图:创建客户端实例时,添加对应意图配置:
const { Client, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildPresences, GatewayIntentBits.GuildMembers ] });
同时需在Discord开发者门户的机器人设置中,开启Privileged Gateway Intents下的Presence Intent和Server Members Intent权限。
- 添加空值防御检查:在读取
presence.status前先判断presence是否存在,避免访问null的属性:
修改循环内代码如下:
for (let i = 0; i < list.length; i++) { // 先处理presence为null的情况 if (!list[i].presence) { if (firstOffline[i] === 1) { timeList[i] = ":white_circle: " + time; firstOffline[i] = 0; } continue; } // 原状态判断逻辑 if (list[i].presence.status !== "offline") { if (list[i].presence.status === "idle") { timeList[i] = ":orange_circle: " + time; } else if (list[i].presence.status === "dnd") { timeList[i] = ":red_circle: " + time; } else { timeList[i] = ":green_circle: " + time; } firstOffline[i] = 1; } else if (firstOffline[i] === 1) { timeList[i] = ":white_circle: " + time; firstOffline[i] = 0; } }
内容的提问来源于stack exchange,提问作者NoobAp17
相关产品推荐
相关产品推荐

