遇到TypeError: Cannot read properties of undefined (reading 'push'),我遗漏了什么?
groupcreate 斜杠命令报错分析 错误信息
TypeError: Cannot read properties of undefined (reading 'push')
at Object.execute (C:\Users\User\Desktop\TestBot\Commands\RolesTest\groupcreate.js:22:20)
相关代码
const { SlashCommandBuilder } = require('discord.js'); const fs = require('fs'); const {groups} = require('../../groups.json') module.exports = { data: new SlashCommandBuilder() .setName('groupcreate') .setDescription('Creates a Role Group') .addStringOption(option =>`your text` option.setName('name') .setDescription('Name for the group') .setRequired(true)),`your text` async execute(interaction) { let group = { name: interaction.options.getString('name'), data: [] } var file = fs.readFileSync('groups.json'); if (file.length == 0) { fs.writeFileSync('groups.json', JSON.stringify([group])) } else { groups.push(group); fs.writeFileSync('groups.json', JSON.stringify(groups, null, 2)) } await interaction.reply({content: `Creating Group: ${interaction.options.getString('name')}`}); }, };
报错原因及忽略的细节
1. JSON导入方式错误
你的groups.json文件应该是直接存储数组(比如初始为空数组[]),但你用了解构赋值const {groups} = require('../../groups.json'),这会尝试从导入的对象中读取groups属性。如果JSON根结构是数组而非包含groups字段的对象,groups变量就会是undefined,调用push自然会报错。
2. 未同步文件动态变化
模块加载时导入的groups是静态值,后续groups.json文件内容变化不会自动更新这个变量。你在execute里读取了文件,但没有把读取的内容解析为JSON并更新groups,导致始终使用初始导入的可能已失效的值。
3. 代码存在冗余语法错误
data字段的SlashCommandBuilder定义里有多余的your text文本,这会破坏命令的结构,可能导致命令无法正确注册或解析,虽然不是当前报错的直接原因,但必须修正。
解决方法
修正JSON导入方式:
如果groups.json直接存储数组,改为直接导入整个数组:let groups = require('../../groups.json');同步文件内容到变量:
在execute函数里,读取文件后重新解析为JSON,确保使用最新的文件内容(注意统一文件路径,避免相对路径问题):async execute(interaction) { let group = { name: interaction.options.getString('name'), data: [] }; const filePath = '../../groups.json'; let fileContent = fs.readFileSync(filePath, 'utf8'); let groups = fileContent.length === 0 ? [] : JSON.parse(fileContent); groups.push(group); fs.writeFileSync(filePath, JSON.stringify(groups, null, 2)); await interaction.reply({content: `Creating Group: ${interaction.options.getString('name')}`}); },移除冗余文本:
修正data部分的命令定义,去掉多余的your text:data: new SlashCommandBuilder() .setName('groupcreate') .setDescription('Creates a Role Group') .addStringOption(option => option.setName('name') .setDescription('Name for the group') .setRequired(true)),
内容的提问来源于stack exchange,提问作者Xhani

