TypeError: component.toJSON不是一个函数,以及在未知行上出现的其他错误discord.js [已解决]

后端开发 2026-07-11

我们正在为Discord机器人实现一个斜杠命令,用来创建表单。

这是一个简化的、最小可复现的示例,产生了类似的结果:

require('dotenv').config()
const discord = require('discord.js')
const client = new discord.Client({ intents: [discord.GatewayIntentBits.Guilds] });

const container = new discord.ContainerBuilder()
    .setAccentColor(0x0099ff)
    .addActionRowComponents(actionRow=>
        actionRow.addComponents(button =>
                button.setCustomId('button').setLabel('Open form').setStyle(discord.ButtonStyle.Primary),
            ))

client.on(discord.Events.ClientReady, (client) => {
    client.channels.cache.get(/*channel*/).send({
        components: [container],
        flags: discord.MessageFlags.IsComponentsV2,
    });
})

client.login(process.env.TOKEN);

运行这段代码时,会得到错误 'TypeError: component.toJSON is not a function'。

当添加其他组件,如分隔符和分区行时,会得到一个 'Invalid Array Length' 错误,错误信息中包含 '[]',并且要求是一个长度大于1 的数组。堆栈跟踪没有指向我们代码中的任意一行,也没有提及我们代码中的任何变量、函数或标识符名称,仅指向模块本身。很难找出究竟是哪个部分引发了问题。

不知何故,如果你尝试打印 container.components[0].components[0],却得到 TypeError: Cannot read properties of undefined (reading 'setCustomId')

网上没有找到其他相关的问题或解答,Stack Overflow或 Google上也没有。 这些错误在我们添加了一个持续时间字段“此表单将在 [hours] 小时后过期”与自定义缩略图后才特别发生,现在使用之前的代码也会得到相同的结果。我们也没有最近更新这个包。

无用 堆栈跟踪:

/workspaces/***/node_modules/@discordjs/builders/dist/index.js:2672
      components: this.components.map((component) => component.toJSON())
                                                               ^

TypeError: component.toJSON is not a function
    at /workspaces/***/node_modules/@discordjs/builders/dist/index.js:2672:64
    at Array.map (<anonymous>)
    at ActionRowBuilder.toJSON (/workspaces/***/node_modules/@discordjs/builders/dist/index.js:2672:35)
    at /workspaces/***/node_modules/@discordjs/builders/dist/index.js:2237:64
    at Array.map (<anonymous>)
    at ContainerBuilder.toJSON (/workspaces/***/node_modules/@discordjs/builders/dist/index.js:2237:35)
    at /workspaces/***/node_modules/discord.js/src/structures/MessagePayload.js:151:46
    at Array.map (<anonymous>)
    at MessagePayload.resolveBody (/workspaces/***/node_modules/discord.js/src/structures/MessagePayload.js:150:49)
    at TextChannel.send (/workspaces/***/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:191:61)

Node.js v24.11.1

解决方案

分区缺少缩略图和按钮,容器不能只包含操作行。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章