search
HomeWeb Front-endJS Tutorial10 Most Frequent Javascript Errors

10 Most Frequent Javascript Errors

Feb 09, 2018 am 10:22 AM
javascriptjsmistake

Data is king. We collected and analyzed the top 10 most frequently occurring JavaScript errors. Rollbar collects all errors for each project and summarizes the number of times each error occurred. We do this by grouping errors based on “fingerprints” (an algorithm used by rollbar, see: https://rollbar.com/docs/grouping-algorithm/). Basically, if the second error is just a duplicate of the first error, we group both errors into the same group. This will give the user a good overview, rather than an overwhelming dump like what you see in the log file.

We focus on the bugs most likely to impact you and your users. To do this, we ranked the errors by studying project sets from various companies. If we only looked at the total number of times each error occurred, the errors produced by a high-volume project might overwhelm other errors, resulting in a data set of errors that would not be relevant to most readers.

Here are the top 10 JavaScript errors:

We have shortened each error description for easier reading. Next, let's dive into each error to determine what causes it and how to avoid creating it.

1. Uncaught TypeError: Cannot read property

If you are a JavaScript developer, you may have seen this error more times than you dare to admit ( LOL…). This error occurs in Chrome when you read a property of an undefined object or call its method. You can easily test (try it out) in the Chrome Developer Console.

There are many reasons why this happens, but a common one is improper initialization of state when rendering UI components.

Let’s look at an example of what happens in a real application: we choose React, but the same applies to Angular, Vue or any other framework.


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>
  );
 }
}

There are two important things to achieve here:

The component's state (e.g. this.state) starts from undefined.

When data is obtained asynchronously, whether it is obtained in the constructor componentWillMount or componentDidMount, the component will be rendered at least once before the data is loaded. When Quiz is first rendered, this.state. items is undefined. This in turn means that the ItemList defines items as undefined and an error appears in the console - "Uncaught TypeError: Cannot read property 'map' of undefined".

This is easily solved. The simplest way: initialize the state in the constructor with sensible default values.


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(&#39;/thedata&#39;).then(res => {
   this.setState({items: res.data});
  });
 }
 render() {
  return (
   <ul>
    {this.state.items.map(item =>
     <li key={item.id}>{item.name}</li>
    )}
   </ul>
  );
 }
}

The specific code in your application may be different, but we hope we have given you enough clues to solve or avoid it in your application This problem arises in . If you haven't yet, keep reading as we'll cover more examples of related errors below.

2. TypeError: ‘undefined’ is not an object

This is an error that occurs when reading a property or calling a method on an undefined object in Safari. You can easily test this in the Safari Developer Console. This is essentially the same Chrome error mentioned in #1, but Safari uses a different error message.

3. TypeError: null is not an object

This is when reading properties or calling on an empty object in Safari An error occurred during the method. You can easily test this in the Safari Developer Console.

Interestingly, null and undefined are not the same in JavaScript, which is why we see two different error messages. undefined is usually a variable that has not been assigned, while null means the value is empty. To verify that they are not equal, try using the strict equality operator ===:

In a real world example, one scenario where this error can occur is : If you try to use the element in JavaScript before the element is loaded. Because the DOM API returns null for a blank object reference.

Any JS code that executes and processes DOM elements should be executed after the DOM element is created. JS code is interpreted from top to bottom as specified in HTML. So, if the DOM element is preceded by a tag, the JS code inside the script tag will be executed when the browser parses the HTML page. This error occurs if the DOM element has not been created before loading the script.

在这个例子中,我们可以通过添加一个事件监听器来解决这个问题,这个监听器会在页面准备好的时候通知我们。 一旦 addEventListener被触发,init() 方法就可以使用 DOM 元素。


<script>
 function init() {
  var myButton = document.getElementById("myButton");
  var myTextfield = document.getElementById("myTextfield");
  myButton.onclick = function() {
   var userName = myTextfield.value;
  }
 }
 document.addEventListener(&#39;readystatechange&#39;, function() {
  if (document.readyState === "complete") {
   init();
  }
 });
</script>
<form>
 <input type="text" id="myTextfield" placeholder="Type your name" />
 <input type="button" id="myButton" value="Go" />
</form>

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"</script>

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

5. TypeError: Object doesn't support property

这是您在调用未定义的方法时发生在 IE 中的错误。 您可以在 IE 开发者控制台中进行测试。

这相当于 Chrome 中的 “TypeError:”undefined“ is not a function” 错误。 是的,对于相同的逻辑错误,不同的浏览器可能具有不同的错误消息。

对于使用 JavaScript 命名空间的 Web 应用程序,这是一个 IE l浏览器的常见的问题。 在这种情况下,99.9% 的原因是 IE 无法将当前名称空间内的方法绑定到 this 关键字。 例如:如果你 JS 中有一个命名空间 Rollbar 以及方法 isAwesome 。 通常,如果您在 Rollbar 命名空间内,则可以使用以下语法调用isAwesome方法:

this.isAwesome();

Chrome,Firefox 和 Opera 会欣然接受这个语法。 另一方面 IE,不会。 因此,使用 JS 命名空间时最安全的选择是始终以实际名称空间作为前缀。

Rollbar.isAwesome();

6. TypeError: ‘undefined' is not a function

当您调用未定义的函数时,这是 Chrome 中产生的错误。 您可以在 Chrome 开发人员控制台和 Mozilla Firefox 开发人员控制台中进行测试。

随着 JavaScript 编码技术和设计模式在过去几年中变得越来越复杂,回调和关闭中的自引用范围也相应增加,这是这种/那种混淆的相当常见的来源。

考虑这个代码片段:


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

执行上面的代码会导致以下错误:“Uncaught TypeError:undefined is not a function”。 你得到上述错误的原因是,当你调用setTimeout()时,实际上是调用window.setTimeout()。 因此,在窗口对象的上下文中定义了一个传递给setTimeout()的匿名函数,该函数没有clearBoard()方法。

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


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

或者,在较新的浏览器中,可以使用bind()方法传递适当的引用:


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

7. Uncaught RangeError: Maximum call stack

这是 Chrome 在一些情况下会发生的错误。 一个是当你调用一个不终止的递归函数。您可以在 Chrome 开发者控制台中进行测试。

此外,如果您将值传递给超出范围的函数,也可能会发生这种情况。 许多函数只接受其输入值的特定范围的数字。 例如:Number.toExponential(digits) 和 Number.toFixed(digits) 接受 0 到 20 的数字,Number.toPrecision(digits) 接受 1 到 21 的数字。


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'

这是 Chrome 中发生的错误,因为读取未定义变量的长度属性。 您可以在 Chrome 开发者控制台中进行测试。

您通常会在数组中找到定义的长度,但是如果数组未初始化或者变量名称在另一个上下文中隐藏,则可能会遇到此错误。让我们用下面的例子来理解这个错误。


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();

2. 用声明的数组调用该函数:


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”。

例如,在 Chrome 浏览器中:

如果测试对象不存在,错误将会抛出 “Uncaught TypeErrorUncaught TypeError: Cannot set property”。

10. ReferenceError: event is not defined

当您尝试访问未定义的变量或超出当前范围的变量时,会引发此错误。 您可以在 Chrome 浏览器中轻松测试。

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


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

相关推荐:

JavaScript 错误处理和堆栈追踪浅析

Javascript 错误处理的几种方法_javascript技巧

JavaScript 错误处理与调试经验总结_javascript技巧

The above is the detailed content of 10 Most Frequent Javascript Errors. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor