【问题标题】:TypeError: Cannot read properties of undefined (reading 'toJSON') - Discord.js slash commandsTypeError:无法读取未定义的属性(读取 \'toJSON\')discord.js 斜杠命令
【发布时间】:2022-08-04 01:54:33
【问题描述】:

我今天尝试在 discord.js 上执行斜杠命令,但我的控制台抛出了一些错误,它无法读取属性 toJSON 可能的解决方案是什么?

这是我的错误:

~/.../stuff/hazy $ node hazy.js
/storage/emulated/0/stuff/hazy/hazy.js:163
  commands.push(command.data.toJSON());
                             ^

TypeError: Cannot read properties of undefined (reading \'toJSON\')
    at Object.<anonymous> (/storage/emulated/0/stuff/hazy/hazy.js:163:30)
    at Module._compile (node:internal/modules/cjs/loader:1099:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

Node.js v17.9.0

这是我的代码:

const { REST } = require(\'@discordjs/rest\');
const { Routes } = require(\'discord-api-types/v9\');
const { token } = require(\'./config.json\');
const fs = require(\'node:fs\');

const commands = [];
const commandFiles = fs.readdirSync(\'./commands\').filter(file => file.endsWith(\'.js\'));

// Place your client and guild ids here
const clientId = \'913559840780091453\';
const guildId = \'912552644462121050\';

for (const file of commandFiles) {
  const command = require(`./commands/${file}`);
  commands.push(command.data.toJSON());
}

const rest = new REST({ version: \'9\' }).setToken(token);

(async () => {
    try {
        console.log(\'Started refreshing application (/) commands.\');

        await rest.put(
            Routes.applicationGuildCommands(clientId, guildId),
            { body: commands },
        );

        console.log(\'Successfully reloaded application (/) commands.\');
    } catch (error) {
        console.error(error);
    }
})();
  • command.data.toJSON 在此对象上不存在。试试JSON.stringify(command.data)
  • 你要我写commands.push(command.data.JSON.stringify(command.data);吗?
  • commands.push(JSON.stringify(command.data));
  • 好吧,在这种情况下,我会尝试两种方法,哈哈
  • @Vincent 错误表明 command.data 未定义。如果该对象上不存在toJSON,则错误将是“...不是函数”。 @coco bar 你的循环遇到了一个没有data 属性的command 对象。检查您的所有命令文件和对象,并确保它们每个都有一个。

标签: javascript node.js discord discord.js slash


【解决方案1】:

从您收到的错误中,我可以看到 data 对象上显然不存在 command 属性。您是否在相应的命令文件中定义/导出了它?

尝试记录 command.data 对象以查看是否弹出任何内容。大概就是这个错误。

【讨论】:

    【解决方案2】:

    代替

    commands.push(command.data.toJSON());
    

    commands.push(JSON.stringify(command.data));
    

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 2021-07-29
      • 2021-12-02
      • 1970-01-01
      • 2023-01-14
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 2020-07-14
      相关资源
      最近更新 更多