Error in maximum call stack size exceeded angular

I have a problem with my Ng2 project for 3 - 4 days. Versions. @angular/cli: 1.0.0-rc.2 node: 6.9.2 os: win32 x64 @angular/common: 2.4.9 @angular/compiler: 2.4.9 @angular/core: 2.4.9 @angular/for...

I have a problem with my Ng2 project for 3 — 4 days.

Versions.

  • @angular/cli: 1.0.0-rc.2
  • node: 6.9.2
  • os: win32 x64
  • @angular/common: 2.4.9
  • @angular/compiler: 2.4.9
  • @angular/core: 2.4.9
  • @angular/forms: 2.4.9
  • @angular/http: 2.4.9
  • @angular/platform-browser: 2.4.9
  • @angular/platform-browser-dynamic: 2.4.9
  • @angular/router: 3.4.9
  • @angular/cli: 1.0.0-rc.2
  • @angular/compiler-cli: 2.4.9

Repro steps.

I run ng serv / ng test or ng build and i have : «ERROR in Maximum call stack size exceeded»

The log given by the failure.

After «ng serve»

$ ng serve
** NG Live Development Server is running on http://localhost:4200 **
Hash: a73c4ecdb8222366629e
Time: 16536ms
chunk    {0} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 405 kB {5} [initial] [rendered]
chunk    {1} main.bundle.js, main.bundle.js.map (main) 41.1 kB {4} [initial] [rendered]
chunk    {2} styles.bundle.js, styles.bundle.js.map (styles) 149 kB {5} [initial] [rendered]
chunk    {3} scripts.bundle.js, scripts.bundle.js.map (scripts) 244 kB {5} [initial] [rendered]
chunk    {4} vendor.bundle.js, vendor.bundle.js.map (vendor) 2.75 MB [initial] [rendered]
chunk    {5} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]

ERROR in Maximum call stack size exceeded
webpack: Failed to compile.

After I save one time and all is alright :

$ ng serve
** NG Live Development Server is running on http://localhost:4200 **
Hash: a73c4ecdb8222366629e
Time: 16536ms
chunk    {0} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 405 kB {5} [initial] [rendered]
chunk    {1} main.bundle.js, main.bundle.js.map (main) 41.1 kB {4} [initial] [rendered]
chunk    {2} styles.bundle.js, styles.bundle.js.map (styles) 149 kB {5} [initial] [rendered]
chunk    {3} scripts.bundle.js, scripts.bundle.js.map (scripts) 244 kB {5} [initial] [rendered]
chunk    {4} vendor.bundle.js, vendor.bundle.js.map (vendor) 2.75 MB [initial] [rendered]
chunk    {5} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]

ERROR in Maximum call stack size exceeded
webpack: Failed to compile.
webpack: Compiling...
Hash: 02fd7618c3e2de3db52e
Time: 9915ms
chunk    {0} 0.chunk.js, 0.chunk.js.map 926 kB {1} {2} {3} {5} [rendered]
chunk    {1} 1.chunk.js, 1.chunk.js.map 397 kB {0} {2} {3} {5} [rendered]
chunk    {2} 2.chunk.js, 2.chunk.js.map 33.1 kB {0} {1} {3} {5} [rendered]
chunk    {3} 3.chunk.js, 3.chunk.js.map 2.96 kB {0} {1} {2} {5} [rendered]
chunk    {4} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 405 kB {9} [initial] [rendered]
chunk    {5} main.bundle.js, main.bundle.js.map (main) 41.1 kB {8} [initial] [rendered]
chunk    {6} styles.bundle.js, styles.bundle.js.map (styles) 149 kB {9} [initial] [rendered]
chunk    {7} scripts.bundle.js, scripts.bundle.js.map (scripts) 244 kB {9} [initial] [rendered]
chunk    {8} vendor.bundle.js, vendor.bundle.js.map (vendor) 2.75 MB [initial] [rendered]
chunk    {9} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]
webpack: Compiled successfully.

And for «ng test» is same.

Any idea to resolve this ?

Comments

@michalSolarz

petebacondarwin

added a commit
to petebacondarwin/angular
that referenced
this issue

Apr 6, 2020

@petebacondarwin

The source-map flattening was throwing an error when there
is a cyclic dependency between source files and source-maps.
The error was either a custom one describing the cycle, or a
"Maximum call stack size exceeded" one.

Now this is handled more leniently, resulting in a partially loaded
source file (or source-map) and a warning logged.

Fixes angular#35727
Fixes angular#35757
Fixes angular/angular-cli#17106
Fixes angular/angular-cli#17115

petebacondarwin

added a commit
to petebacondarwin/angular
that referenced
this issue

Apr 6, 2020

@petebacondarwin

The source-map flattening was throwing an error when there
is a cyclic dependency between source files and source-maps.
The error was either a custom one describing the cycle, or a
"Maximum call stack size exceeded" one.

Now this is handled more leniently, resulting in a partially loaded
source file (or source-map) and a warning logged.

Fixes angular#35727
Fixes angular#35757
Fixes angular/angular-cli#17106
Fixes angular/angular-cli#17115

kara

pushed a commit
to angular/angular
that referenced
this issue

Apr 6, 2020

@petebacondarwin

@kara

The source-map flattening was throwing an error when there
is a cyclic dependency between source files and source-maps.
The error was either a custom one describing the cycle, or a
"Maximum call stack size exceeded" one.

Now this is handled more leniently, resulting in a partially loaded
source file (or source-map) and a warning logged.

Fixes #35727
Fixes #35757
Fixes angular/angular-cli#17106
Fixes angular/angular-cli#17115

PR Close #36452

Ситуация: заказчик попросил разместить на странице кликабельную картинку, а чтобы на неё обратило внимание больше посетителей, попросил сделать вокруг неё моргающую рамку. Логика моргания в скрипте очень простая:

  1. В первой функции находим на странице нужный элемент.
  2. Добавляем рамку с какой-то задержкой (чтобы она какое-то время была на экране).
  3. Вызываем функцию убирания рамки.
  4. Внутри второй функции находим тот же элемент на странице.
  5. Убираем рамку с задержкой.
  6. Вызываем первую функцию добавления рамки.

Код простой, поэтому делаем всё в одном файле:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Pulse</title>
	<style type="text/css">
	/*	рамка, которая будет моргать	*/
		.pulse { box-shadow: 0px 0px 4px 4px #AEA79F; }
	</style>
</head>
<body>
	<div id="pulseDiv"> 
    	<a href="#">
      		<div id="advisersDiv">
        		<img src="https://thecode.media/wp-content/uploads/2020/08/photo_2020-08-05-12.04.57.jpeg">
        	</div>
      	</a>
</div>
<!-- подключаем jQuery -->
<script src="https://yastatic.net/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<!-- наш скрипт -->
<script type="text/javascript">
	// добавляем рамку
	function fadeIn() {
		// находим нужный элемент и добавляем рамку с задержкой
  	$('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
  	// затем убираем рамку
  	fadeOut();
	};
	// убираем рамку
	function fadeOut() {
		// находим нужный элемент и убираем рамку с задержкой
   	$('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
   	// затем добавляем 
   	fadeIn();
	};
	// запускаем моргание рамки
	fadeIn();
</script>

</body>
</html>

Но при открытии страницы в браузере мы видим, что ничего не моргает, а в консоли появилась ошибка:

❌ Uncaught RangeError: Maximum call stack size exceeded

Что это значит: в браузере произошло переполнение стека вызовов и из-за этого он не может больше выполнять этот скрипт.

Переполнения стека простыми словами означает вот что:

  1. Когда компьютер что-то делает, он это делает последовательно — 1, 2, 3, 4.
  2. Иногда ему нужно отвлечься от одного и сходить сделать что-то другое — а, б, в, г, д. Получается что-то вроде 1, 2, 3 → а, б, в, г, д → 4.
  3. Вот эти переходы 3 → а и д → 4 — это компьютеру нужно запомнить, что он выполнял пункт 3, и потом к нему вернуться.
  4. Каждое запоминание, что компьютер бросил и куда ему нужно вернуться, — это называется «вызов».
  5. Вызовы хранятся в стеке вызовов. Это стопка таких ссылок типа «когда закончишь вот это, вернись туда».
  6. Стек не резиновый и может переполняться.

Что делать с ошибкой Uncaught RangeError: Maximum call stack size exceeded

Эта ошибка — классическая ошибка переполнения стека во время выполнения рекурсивных функций.

Рекурсия — это когда мы вызываем функцию внутри самой себя, но чуть с другими параметрами. Когда параметр дойдёт до конечного значения, цепочка разматывается обратно и функция собирает вместе все значения. Это удобно, когда у нас есть чёткий алгоритм подсчёта с понятными правилами вычислений.

В нашем случае рекурсия возникает, когда в конце обеих функций мы вызываем другую: 

  1. Функции начинают бесконтрольно вызывать себя бесконечное число раз.
  2. Стек вызовов начинает запоминать вызов каждой функции, чтобы, когда она закончится, вернуться к тому, что было раньше.
  3. Стек — это определённая область памяти, у которой есть свой объём.
  4. Вызовы не заканчиваются, и стек переполняется — в него больше нельзя записать вызов новой функции, чтобы потом вернуться обратно.
  5. Браузер видит всё это безобразие и останавливает скрипт.

То же самое будет, если мы попробуем запустить простую рекурсию слишком много раз:

Что означает ошибка Uncaught RangeError: Maximum call stack size exceeded

Как исправить ошибку Uncaught RangeError: Maximum call stack size exceeded

Самый простой способ исправить эту ошибку — контролировать количество рекурсивных вызовов, например проверять это значение на входе. Если это невозможно, то стоит подумать, как можно переделать алгоритм, чтобы обойтись без рекурсии.

В нашем случае проблема возникает из-за того, что мы вызывали вторые функции бесконтрольно, поэтому они множились без ограничений. Решение — ограничить вызов функции одной секундой — так они будут убираться из стека и переполнения не произойдёт:

<script type="text/javascript">
// добавляем рамку
function fadeIn() {
	// находим нужный элемент и добавляем рамку с задержкой
	$('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
	// через секунду убираем рамку
	setTimeout(fadeOut,1000)
};
// убираем рамку
function fadeOut() {
	// находим нужный элемент и убираем рамку с задержкой
 	$('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
 	// через секунду добавляем рамку
	setTimeout(fadeIn,1000)
};
// запускаем моргание рамки
fadeIn();
</script>

Что означает ошибка Uncaught RangeError: Maximum call stack size exceeded

Вёрстка:

Кирилл Климентьев

negue

negue

Posted on Dec 16, 2019

Wow…. who would’ve known that the next issue would be right at the corner so soon. 😁

I’m working on a markdown component, and I needed a list of colon emoji keys’s (:smile:) to have simple overview for them 😄

While angular was running, I created this > file < nothing happened.

When I imported it…

ERROR in RangeError: Maximum call stack size exceeded happened

…. ok what … why?!

Usually this error means, some module imported a different one which imported the previous one, which imported «the different»-one … and so on.

Or it means just any methods called itself until the stack exceeded, but it wasn’t a runtime error, it was a compiler error.

Ok. Weird.

What did I do before it… «just added a file»… right?

To make sure it is not a hiccup again, I restarted angular/typescript.

The error still happens.

Removed the file and its working again?!

Lets try to debug it again.

Added the file back and started angular in verbose mode.

ERROR in RangeError: Maximum call stack size exceeded
    at needsIndentation 
        function needsIndentation(parent, node1, node2) {
            parent = skipSynthesizedParentheses(parent);
            node1 = skipSynthesizedParentheses(node1);
            node2 = skipSynthesizedParentheses(node2);

Sadly I haven’t took a deep-dive into typescript (yet), but today wouldn’t be the day either 😁, but maybe there was already anything anywhere => searched for the first 2 lines, but I couldn’t find anything useful.

Solution. 🎉

Use an array of strings and then just .join() them together. > Gist <

Issue

I am using a Direct Web Remoting (DWR) JavaScript library file and am getting an error only in Safari (desktop and iPad)

It says

Maximum call stack size exceeded.

What exactly does this error mean and does it stop processing completely?

Also any fix for Safari browser (Actually on the iPad Safari, it says

JS:execution exceeded timeout

which I am assuming is the same call stack issue)

Solution

It means that somewhere in your code, you are calling a function which in turn calls another function and so forth, until you hit the call stack limit.

This is almost always because of a recursive function with a base case that isn’t being met.

Viewing the stack

Consider this code…

(function a() {
    a();
})();

Here is the stack after a handful of calls…

Web Inspector

As you can see, the call stack grows until it hits a limit: the browser hardcoded stack size or memory exhaustion.

In order to fix it, ensure that your recursive function has a base case which is able to be met…

(function a(x) {
    // The following condition 
    // is the base case.
    if ( ! x) {
        return;
    }
    a(--x);
})(10);

Answered By — alex

Понравилась статья? Поделить с друзьями:
  • Error in mapinfo file access library
  • Error in main wine
  • Error in main webpack
  • Error in main please install winbind before installing microsoft office 2016
  • Error in main please install winbind before installing microsoft office 2013