How to fix JavaScript RangeError Maximum call stack size exceeded
November 16, 2021
How to fix JavaScript RangeError: Maximum call stack size exceeded:
RangeError: Maximum call stack size exceeded error occurs mostly if your code has infinite recursion. i.e. a recursion block that is running infinitely.
JavaScript stops a program if it finds any recursive block that is not stopped.
Let’s take a look at the program below:
function getResult(){
getResult();
}
getResult();
It calls getResult and getResult is calling itself again. So, this program will move to an infinite loop. It will not stop.
It will throw the maximum call stack size exceeded error:
Recursive call in multiple methods:
Another issue could be the call is running between two or more methods. For example:
function getResult(){
getResult2();
}
function getResult2(){
getResult()
}
getResult();
In this example, getResult calls getResult2 and getResult2 calls getResult. It will run indefinitely. These types of functions are hard to find because we can have any number of methods in a chain that is causing this problem.
Debugging this issue:
If you look at the logs, it shows the method and class names. It also shows the line number of that file. If you look at the logs, you can find out the culprit file and put some more logs to debug it further.
You might also get this error for multiple imports of a same file. Try to get to the problamatic file and you can debug it easily.
How to fix this issue:
The only way to fix this issue is by making sure that it is not running for infinite time.
In some cases, it might run infinite time only for some specific cases. For example, let’s take a look at the below code snippet:
function getResult(){
try{
fetchData();
}catch(e){
getResult();
}
}
Suppose, fetchData is used to fetch data from a server. And, if it throws an exception, we are calling getResult again. So, if fetchData throws exception always, this function will keep running for infinite amount of time.
You can also add debug points to find the root cause.