Discord国际象棋Bot变量初始化错误排查求助
解决"Cannot access 'games' before initialization"错误
这不是Node.js的Bug,完全是JavaScript块级作用域与暂时性死区导致的问题。
你的代码里,if代码块的最后一行重新声明了const games = JSON.parse(...)。在JavaScript中,let/const声明的变量会被提升到当前块的顶部,但会处于未初始化的暂时性死区。这意味着整个if块内部,所有对games的引用都会优先指向这个块级的games变量,而非外部的全局/函数级变量。当你在if块第一行执行console.log(games)时,访问的是块内还未完成初始化的games,因此触发了"Cannot access 'games' before initialization"错误。
修复方案
方案1:删除块内重复的变量声明
你已经修改了games对象并写入文件,没必要重新读取并声明同名变量,直接复用外部变量即可:
const games = JSON.parse(fs.readFileSync("./lib/database/games/chess/chess_games.json")) console.log(games, 'outside if statement') if (games[interaction.guild.id] == undefined) { console.log(games, 'inside if statement') games[interaction.guild.id] = { games: {}, players: {}, amount_of_games: 0 } fs.writeFileSync("./lib/database/games/chess/chess_games.json", JSON.stringify(games, null, 2)); // 移除这里的const games声明,直接使用外部的games变量 }
方案2:如果需要重新读取文件,更换变量名
如果确实需要重新读取最新的文件内容,给新变量起个不同的名字,避免作用域冲突:
const games = JSON.parse(fs.readFileSync("./lib/database/games/chess/chess_games.json")) console.log(games, 'outside if statement') if (games[interaction.guild.id] == undefined) { console.log(games, 'inside if statement') games[interaction.guild.id] = { games: {}, players: {}, amount_of_games: 0 } fs.writeFileSync("./lib/database/games/chess/chess_games.json", JSON.stringify(games, null, 2)); // 换个变量名,比如updatedGames const updatedGames = JSON.parse(fs.readFileSync("./lib/database/games/chess/chess_games.json")) // 后续使用updatedGames进行操作 }
额外说明
用var声明时也出问题,是因为var的变量提升会覆盖外部变量,但var没有暂时性死区,不过块内的var games会被提升到函数/全局作用域顶部,导致外部的games被提前覆盖为undefined,同样引发异常。本质还是同名变量的作用域冲突。
内容的提问来源于stack exchange,提问作者EntropicBlackhole
相关产品推荐
相关产品推荐

