10种最常见的 JS 错误

468 阅读5分钟

image.png

1. Uncaught TypeError: Cannot read property

如果你是一个 JavaScript 开发人员,可能你看到这个错误的次数比你敢承认的要多(LOL…)。当你读取一个未定义的对象的属性或调用其方法时,这个错误会在 Chrome 中出现。 您可以很容易的在 Chrome 开发者控制台中进行测试(尝试)。

image.png 原因:在渲染 UI 组件时对于状态的初始化操作不当。 案例:

class Quiz extends Component {
 componentWillMount() {
  axios.get('/thedata').then(res => {
   this.setState({items: res.data});
  });
 }
 render() {
  return (
   <ul>
    {this.state.items.map(item =>
     <li key={item.id}>{item.name}</li>
    )}
   </ul>
  );
 }
}

组件的状态(例如 this.state)从 undefined 开始。

解决:在构造函数中用合理的默认值来初始化 state。

class Quiz extends Component {
 // Added this:
 constructor(props) {
  super(props);
  // Assign state itself, and a default value for items
  this.state = {
   items: []
  };
 }
 componentWillMount() {
  axios.get('/thedata').then(res => {
   this.setState({items: res.data});
  });
 }
 render() {
  return (
   <ul>
    {this.state.items.map(item =>
     <li key={item.id}>{item.name}</li>
    )}
   </ul>
  );
 }
}

2.TypeError: ‘undefined' is not an object

3. TypeError: null is not an object

在 JavaScript 中,null 和 undefined 是不一样的,这就是为什么我们看到两个不同的错误信息。undefined 通常是一个尚未分配的变量,而 null 表示该值为空。 发生的场景:如果在加载元素之前尝试在 JavaScript 中使用元素。

4. (unknown): Script error

当未捕获的 JavaScript 错误(通过window.onerror处理程序引发的错误,而不是捕获在try-catch中)被浏览器的跨域策略限制时,会产生这类的脚本错误。 例如,如果您将您的 JavaScript 代码托管在 CDN 上,则任何未被捕获的错误将被报告为“脚本错误” 而不是包含有用的堆栈信息。这是一种浏览器安全措施,旨在防止跨域传递数据,否则将不允许进行通信。

要获得真正的错误消息,请执行以下操作:

1. 发送 ‘Access-Control-Allow-Origin' 头部

将 Access-Control-Allow-Origin 标头设置为 * 表示可以从任何域正确访问资源。 如有必要,您可以将域替换为您的域:例如,Access-Control-Allow-Origin:www.example.com。 但是,处理多个域会变得棘手,如果你使用 CDN,可能由此产生更多的缓存问题会让你感觉到这种努力并不值得。 在这里看到更多。

这里有一些关于如何在各种环境中设置这个头文件的例子:

Apache

在 JavaScript 文件所在的文件夹中,使用以下内容创建一个 .htaccess 文件:

Header add Access-Control-Allow-Origin "*"

Nginx

将 add_header 指令添加到提供 JavaScript 文件的位置块中:

location ~ ^/assets/ {
  add_header Access-Control-Allow-Origin *;
}

HAProxy

将以下内容添加到您为 JavaScript 文件提供资源服务的后端:

rspadd Access-Control-Allow-Origin:\ *

2. 在 <script> 中设置 crossorigin="anonymous"

在您的 HTML 代码中,对于您设置了Access-Control-Allow-Origin header 的每个脚本,在 script 标签上设置crossorigin =“anonymous”。在脚本标记中添加 crossorigin 属性之前,请确保验证上述 header 正确发送。 在 Firefox 中,如果存在crossorigin属性,但Access-Control-Allow-Origin头不存在,则脚本将不会执行。

6. TypeError: ‘undefined' is not a function

发生场景:调用未定义的函数。

function testFunction() {
 this.clearLocalStorage();
 this.timer = setTimeout(function() {
  this.clearBoard();  // what is "this"?
 }, 0);
};

你得到上述错误的原因是,当你调用setTimeout()时,实际上是调用window.setTimeout()。 因此,在窗口对象的上下文中定义了一个传递给setTimeout()的匿名函数,该函数没有clearBoard()方法。

一个传统的,旧浏览器兼容的解决方案是简单地将您的 this 保存在一个变量,然后可以由闭包继承。

function testFunction () {
 this.clearLocalStorage();
 var self = this;  // save reference to 'this', while it's still this!
 this.timer = setTimeout(function(){
  self.clearBoard(); 
 }, 0);
};

解决2:改变this指向

function testFunction () {
 this.clearLocalStorage();
 this.timer = setTimeout(this.reset.bind(this), 0); // bind to 'this'
};
function testFunction(){
  this.clearBoard();  //back in the context of the right 'this'!
};

7. Uncaught RangeError: Maximum call stack

原因1:当你调用一个不终止的递归函数。

原因2:将值传递给超出范围的函数

var a = new Array(4294967295); //OK
var b = new Array(-1); //range error
var num = 2.555555;
document.writeln(num.toExponential(4)); //OK
document.writeln(num.toExponential(-2)); //range error!
num = 2.9999;
document.writeln(num.toFixed(2));  //OK
document.writeln(num.toFixed(25)); //range error!
num = 2.3456;
document.writeln(num.toPrecision(1));  //OK
document.writeln(num.toPrecision(22)); //range error!

8. TypeError: Cannot read property ‘length'

如果数组未初始化或者变量名称在另一个上下文中隐藏,则可能会遇到此错误。

var testArray = ["Test"];
function testFunction(testArray) {
  for (var i = 0; i < testArray.length; i++) {
   console.log(testArray[i]);
  }
}
testFunction();

当你用参数声明一个函数时,这些参数变成了函数作用域内的本地参数。这意味着即使你函数外有名为 testArray 的变量,在一个函数中具有相同名字的参数也会被视为本地参数。

解决:

  1. 删除函数声明语句中的参数(事实上你想访问那些声明在函数之外的变量,所以你不需要函数的参数):
var testArray = ["Test"];
/* Precondition: defined testArray outside of a function */
function testFunction(/* No params */) {
  for (var i = 0; i < testArray.length; i++) {
   console.log(testArray[i]);
  }
}
testFunction();
  1. 用声明的数组调用该函数:
var testArray = ["Test"];
function testFunction(testArray) {
  for (var i = 0; i < testArray.length; i++) {
   console.log(testArray[i]);
  }
}
testFunction(testArray);

9. Uncaught TypeError: Cannot set property

当我们尝试访问一个未定义的变量时,它总是返回 undefined,我们不能获取或设置任何未定义的属性。 在这种情况下,应用程序将抛出 “Uncaught TypeError: Cannot set property”。

image.png

10. ReferenceError: event is not defined

当您尝试访问未定义的变量或超出当前范围的变量时,会引发此错误。

image.png

如果在使用事件处理系统时遇到此错误,请确保使用传入的事件对象作为参数。像 IE 这样的旧浏览器提供了一个全局变量事件,但并不是所有浏览器都支持。像 jQuery 这样的库试图规范化这种行为。尽管如此,最好使用传入事件处理函数的函数。

function myFunction(event) {
  event = event.which || event.keyCode;
  if(event.keyCode===13){
    alert(event.keyCode);
  }
}