使用新版discord.js开发机器人登录时遇TypeError: Object.hasOwn is not a function
Discord.js登录报错:TypeError: Object.hasOwn is not a function
报错信息
/home/max/Schreibtisch/Discord Bots/Perplex/node_modules/discord.js/src/util/Util.js:279 if (!Object.hasOwn(given, key) || given[key] === undefined) { ^ TypeError: Object.hasOwn is not a function at mergeDefault (/home/max/Schreibtisch/Discord Bots/Perplex/node_modules/discord.js/src/util/Util.js:279:17) at new BaseClient (/home/max/Schreibtisch/Discord Bots/Perplex/node_modules/discord.js/src/client/BaseClient.js:25:20) at new Client (/home/max/Schreibtisch/Discord Bots/Perplex/node_modules/discord.js/src/client/Client.js:43:5) at Object.<anonymous> (/home/max/Schreibtisch/Discord Bots/Perplex/src/bot.js:26:16) at Module._compile (node:internal/modules/cjs/loader:1108:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10) at Module.load (node:internal/modules/cjs/loader:988:32) at Function.Module._load (node:internal/modules/cjs/loader:828:14) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12) at node:internal/main/run_main_module:17:47
机器人代码
const { Client, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [GatewayIntentBits.Guilds] }); client.on('ready', () => { console.log(`Logged in as ${client.user.tag}!`); }); client.on('interactionCreate', async (interaction) => { if (!interaction.isChatInputCommand()) return; if (interaction.commandName === 'ping') { await interaction.reply('Pong!'); } }); client.login('token');
问题分析
报错根源是Node.js版本不足。Object.hasOwn是Node.js 16.9.0及以上版本才支持的原生方法,而新版discord.js(v14及后续版本)明确要求Node.js版本必须≥16.9.0,版本不匹配就会触发这个错误。
解决方案
- 先检查当前Node.js版本:
node -v - 若版本低于16.9.0,升级Node.js到符合要求的版本:
- 使用nvm(Node版本管理器)的话,执行
nvm install 16或nvm install latest安装指定版本或最新稳定版 - 也可直接下载对应版本的安装包手动安装
- 使用nvm(Node版本管理器)的话,执行
- 升级完成后,重新运行机器人代码即可解决问题。
内容的提问来源于stack exchange,提问作者gokimax
相关产品推荐
相关产品推荐

