前端报错排查指南
🔍 错误定位流程
1. 控制台错误分类
// 常见错误类型 - SyntaxError(语法错误) - ReferenceError(引用错误) - TypeError(类型错误) - RangeError(范围错误) - NetworkError(网络错误) - DOMException(DOM 操作错误)
2. 错误信息解读
Uncaught TypeError: Cannot read property 'name' of undefined at UserProfile.vue:45 at Array.map (<anonymous>) at getUserData (api.js:12)
关键信息提取:
- 错误类型:
TypeError - 错误描述: 尝试读取
undefined的name属性 - 调用栈: 从
UserProfile.vue:45→api.js:12 - 触发操作:
Array.map调用
🛠️ 常见错误及解决方案
1. TypeError 类错误
// 错误示例 let user = null; console.log(user.name); // Cannot read property 'name' of null // ✅ 解决方案 // 1. 可选链操作符 console.log(user?.name); // 2. 默认值设置 console.log((user || {}).name); // 3. 条件判断 if (user && user.name) { console.log(user.name); }
2. ReferenceError 类错误
// 错误示例 console.log(undeclaredVar); // undeclaredVar is not defined // ✅ 解决方案 // 1. 检查变量声明 let undeclaredVar = 'value'; // 2. 检查作用域 function test() { // 使用 let/const 而不是 var 避免变量提升问题 console.log(myVar); // ❌ 暂时性死区 let myVar = 'test'; }

