Unexpected strict mode reserved word как исправить

#android #html #angularjs #cordova #strict

#android #html #angularjs #cordova #strict

#Android #HTML #angularjs #кордова #строгий

Вопрос:

В настоящее время я разрабатываю приложение для мобильных телефонов с использованием AngularJS и cordova 3.2.

Некоторые из моих игроков сообщают, что приложение не запускается на их устройствах. Эти устройства перечислены ниже.

  • optimus p880 (версия Android 4.0.3)
  • Lifetab фон Медион (версия Adroid 4.0.3)
  • Sony Ericsson Xperia mini pro (Android 4.0.4)

Так что, похоже, это как-то связано с этой версией Android 4.0.3 / 4.

Не запуск означает, что приложение cordova запускается, но что angularjs завершает работу до его запуска, потому что все элементы, к которым ng-cloak присоединен класс (который в моем случае установлен для полного корневого окна), остаются скрытыми. Таким образом, пользователь ничего не видит.

Проблема в том, что у меня нет ни одного из этих устройств, чтобы протестировать его, но один игрок прислал мне логи своего устройства, сказав

 Uncaught SyntaxError: Unexpected strict mode reserved word
 

С помощью номера строки и имени файла я мог определить, что проблема вызвана приведенным ниже кодом (его из angular.js файл версии v1.2.16 в строке 3878). Проблема, похоже, изложена в заявлении throw err;

 (#3878)
function createInternalInjector(cache, factory) {

  function getService(serviceName) {
    if (cache.hasOwnProperty(serviceName)) {
      if (cache[serviceName] === INSTANTIATING) {
        throw $injectorMinErr('cdep', 'Circular dependency found: {0}', path.join(' <- '));
      }
      return cache[serviceName];
    } else {
      try {
        path.unshift(serviceName);
        cache[serviceName] = INSTANTIATING;
        return cache[serviceName] = factory(serviceName);
      } catch (err) {
        if (cache[serviceName] === INSTANTIATING) {
          delete cache[serviceName];
        }
        throw err; /*** THE ERROR APPLIES HERE! **/
      } finally {
        path.shift();
      }
    }
  }
 

Я не могу точно сказать, что здесь происходит. Приложения отлично работают на других устройствах и других версиях Android.

Есть ли у кого-нибудь из вас идеи, как я мог бы решить эту проблему для игроков?

Комментарии:

1. Нет идей? Это действительно блокирует меня, и я хотел бы получить решение!

2. Как называются ваши службы? Однажды я получил эту ошибку, когда попытался назвать функцию с помощью зарезервированного (будущего) слова. У вас, вероятно, то же самое. Не удаляйте 'use strict' директивы только из-за этого.

Ответ №1:

Для нас это происходит только в обычном браузере Android 4.0.4 Galaxy S2 (и веб-просмотр приложения) и может быть устранено путем удаления 'use strict;' из нашего app.js .

Я отследил код-нарушитель с помощью консоли.регистрация значения fn.toString().substring(0,150) в angular.js annotate функция и проверка журналов в Weinre после нажатия about:debug кнопки в браузере Stock, которая включает консоль в браузере Stock. Может помочь вам отследить проблемную строку в вашем собственном коде. Возможно, не все получают ошибку на annotate() шаге. Вы должны увидеть строку в журнале консоли.

Galaxy S3 с точно такой же ОС и браузером в порядке… поди разберись.

Все еще ищу способ получить 'use strict'; там и не получить ошибку. Обертывание всего этого в IIFE не помогло, и в этом случае все равно появляется ошибка.

Комментарии:

1. Я пока не нашел решения, я просто удалил 'use strict' все свои файлы…

Robin Jangu

Posted On: April 16, 2018

view count26954 Views

Read time2 Min Read

Remember when you were a mere beginner in JavaScript, while learning you must have come across the term ‘reserved words’. These are the words that you can’t use as names for variables. Apart from mainstream keywords like break, var, if…else etc. there are many more reserved keywords.

SyntaxError: «x» is a reserved identifier  (Firefox)

SyntaxError: Unexpected reserved word (Chrome)

Following will be the error messages you will receive if by accident you use such words. Seasoned JS developers too commit such blunders while scripting.

Strict mode

Strict mode has become a necessity because of its many benefits. It keeps in check and streamlines the code flow, error debugging too becomes very easy. I wouldn’t say that it has shortcomings but you need to be extra careful while implementing this.

In addition to the already existing reserved keywords, Strict mode reserves a few more keywords like implements, interface, let, package, private, protected, public, as, yield and static.

<!DOCTYPE html>

<html>

<body>

<h2>With «use strict»:</h2>

<h3>Using a reserved word as variable name, is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>

«use strict»;

var public = ‘Thanos’;  // This will cause an error (public is reserved in strict mode).

</script>

</body>

</html>

Unexpected syntax error

Now we change the variable name to avengerEnemy, now it will work.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<!DOCTYPE html>

<html>

<body>

<h2>With «use strict»:</h2>

<h3>No reserved word used</h3>

<p>Activate debugging in your browser (F12) to see the avengerEnemy.</p>

<script>

«use strict»;

var avengerEnemy = ‘Thanos’;  //  avengerEnemy is not a reserved word in strict mode.

console.log(avengerEnemy);

</script>

</body>

</html>

error debugging, reserved keywords

If you still get the same error, it may be due to the outdated browser version. Try updating the browser, as the old versions have old reserved words that need to be revised.
Happy scripting!

LambdaTest, Cross browser testing

Author Profile
Author Profile
Author Profile

Author’s Profile

Robin Jangu

Robin is a Tech Blogger and Social Media Marketer.

Got Questions? Drop them on LambdaTest Community. Visit now

Test your websites, web-apps or mobile apps seamlessly with LambdaTest.

  • Selenium, Cypress, Playwright & Puppeteer Testing
  • Real Devices Cloud
  • Native App Testing
  • Appium Testing
  • Live Interactive Testing
  • Smart Visual UI Testing

Book a Demo

#LambdaTestYourBusiness- Holiday Season

Yesterday, while working with some asynchronous JavaScript code being managed through the use of ES6 Generators and coroutines, I was getting an error that tripped me up for a good 10-minutes. The Node.js compiler was telling me that my use of the «yield» keyword was invalid:

SyntaxError: Unexpected strict mode reserved word

The code that contained the «yield» keyword was a simple assignment operator that looked something like this:

'use strict'

function* createGenerator() {

	var x = ! yield Promise.resolve( false );

}

createGenerator().next();

While there is almost nothing going on in this code, there is clearly a problem; and, it has to do with the fact that the «yield» keyword has very low precedence. Precedence determines the order in which parts of an expression are evaluated. So, components of an expression with higher precedence are evaluated sooner and components with lower precedence are evaluated later. Remember PEMDAS from your middle-school math class? Precedence is why the (M) multiplication is evaluated before the (A) addition in the following expression: «3+4*2».

The very low precedence of the «yield» operator (2) and the very high precedence of the Logical-Not operator (16) means that my expression:

! yield Promise.resolve( false )

… is actually being interpreted as:

( ! yield ) Promise.resolve( false )

… which makes the compiler think that I’m trying to use «yield» as some sort of a reference, which is not allowed in strict mode.

In order to change this interpretation of the expression, I have to use Grouping — which has the highest precedence (20) — so that the «yield» operator is correctly associated with the Promise and not with the Logical-Not operator:

! ( yield Promise.resolve( false ) )

Now, the code runs without error because it is clear that the «yield» operator applies to the Promise within the Grouping. And then, the Logical-Not operator gets applied to Grouping.

Most of the time, I use Grouping to make sure my code is explicit. I may be able to reference operator precedence in this post (thanks to the Mozilla Developer Network); but, believe you me, I don’t keep these relative numbers in my head. As such, I use Grouping to ensure the code behaves the way I want it to. yield, being a somewhat magical construct in JavaScript, still trips me up. And, I’m sure it will for a while; but, at least now I’ll know what this JavaScript error means the next time I see it in my Node.js application.

Want to use code from this post?
Check out the license.

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!

Понравилась статья? Поделить с друзьями:
  • Unexpected store exception windows 10 ошибка синий экран
  • Unexpected store exception windows 10 error
  • Unexpected server error please try again if this continues please contact riot support перевод
  • Unexpected runtime error перевод
  • Unexpected runtime error на телевизоре