Skip to content

ReferenceError: x 是不 定义

错误信息

                x 是不 定义
              

快速摘要

你 referenced 变量 name 那个 JavaScript doesn't know 关于 — 它是 从不 declared 使用 `let`, `const`, or `var` in 任何 accessible 作用域.

为什么发生

  • Typo in 变量 name

  • Forgot 到 declare 变量使用 let, const, or var

  • 变量 exists in 不同作用域 and isn't accessible 这里

最小示例

✗ 错误代码
console.log(userName);
✓ 修复代码
const userName = "Alice";
console.log(userName);

用户名 是从不 declared, 所以 JavaScript throws ReferenceError — declare 它使用 const 之前 using 它.

如何诊断

  • 检查 spelling 的变量 name 针对它的 declaration

  • 验证变量是 declared 使用 let, const, or var 之前 use

  • 检查作用域 — 是 declaration 可见从 哪里错误 occurs?

如何修复

  • Declare 变量使用 const or let 之前 using 它

  • Fix typo 到 match declared name

  • Move declaration 到作用域 accessible 从 usage site

如何预防

  • 总是 declare 变量使用 const or let — 从不 use bare assignments

  • 启用 ESLint 使用 no-undef 规则到 catch undeclared 变量

相关资源

相关术语

相关课程

  • 变量

    学习如何 JavaScript 变量工作

相关练习

← 返回语言