Меню

Ошибка typeerror cannot read property range of undefined

The error:

Cannot read property “range” from undefined

Means that getting range from event object e failed.

If you are running the code from inside the script editor, you will get a range error. In the case of a simple onEdit() trigger, you can only test the code by actually editing a cell. The e event variable will not have anything assigned to it unless you actually edit a cell. That e variable will be assigned an event object when the event (a cell edit) happens.

The function name onEdit() is a reserved function name. In order for the onEdit() function to run when a cell is edited, all you need to do is create a function of that name, as opposed to going through a set-up process to assign an event to a function name. onEdit() is a simple trigger. And «installable» trigger needs to be set-up.

I ran your code, and don’t get any range errors, if I trigger it by editing a cell.

I am getting an error stating that I don’t have permission to send an email. Which is because the trigger is a «simple» trigger. You may need to create an installable trigger in order to have permission to send the email.

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Comments

@thomasturrell

Karma version 5.2.3
Node version 14.15.2

After running the tests Chrome exits and I get the following error:

ERROR [karma-server]: UnhandledRejection: Cannot read property 'range' of undefined
ERROR [karma-server]: TypeError: Cannot read property 'range' of undefined

I suspect this to be related to #3571, node version 14.15.1 works correctly.

Please let me know if I need to provide more information.

@devoto13

I don’t think this issue is in Karma core. From #3571 it looks like the issue is in the @angular-devkitbuild-angular plugin. I’ve tested with fresh @angular/cli@11 project and issue is not reproducible. Please consider below options:

  • stick with older Node version
  • upgrade to latest Angular
  • report bug to Angular CLI repository with minimal reproduction if you’re also using Angular 9 as in Karma test cases breaking in node 15.1 #3571. Angular 9 is an LTS release, so they may issue a fix.
  • debug this issue further and figure out if this is a Node regression, then it should be reported to Node itself (which is likely the case given that it broke in the patch release)

In any case, there is nothing we can do on the Karma core to fix issue in the third-party plugin as we don’t develop this plugin.

Happy to re-open if you provide a minimal reproduction showing that this issue is caused by the Karma core.

@johnjbarton

FWIW I tested locally against 14.15.1 and 14.15.2 so any issue between these versions isn’t visible to our tests.

@tbprojects

Unfortunately I have the same issue in my test project. Tests work on NodeJS 14.15.1, but fails on 14.15.2 with exception:

UnhandledRejection: Cannot read property 'range' of undefined

@johnjbarton

@tbprojects Open up karma/lib/server.js and find

this.log.error(`UnhandledRejection: ${error.message || String(error)}`)

Add a line above:

console.error("UnhandledRejection", error.stack || "bah!")

The message should include the stack and that will help us.

@devoto13

@tbprojects Thanks! I’m able to reproduce it using your repository. For some reason it does not reproduce in my freshly-generated Angular CLI 11 project. I’ll check what is different tomorrow and post back.

@wvankuipers

@tbprojects Open up karma/lib/server.js and find

this.log.error(`UnhandledRejection: ${error.message || String(error)}`)

Add a line above:

console.error("UnhandledRejection", error.stack || "bah!")

The message should include the stack and that will help us.

UnhandledRejection TypeError: Cannot read property 'range' of undefined
    at handleRangeHeaders (/node_modules/webpack-dev-middleware/lib/util.js:131:21)
    at processRequest (/node_modules/webpack-dev-middleware/lib/middleware.js:98:19)
    at ready (/node_modules/webpack-dev-middleware/lib/util.js:53:12)
    at handleRequest (/node_modules/webpack-dev-middleware/lib/util.js:182:5)
    at /node_modules/webpack-dev-middleware/lib/middleware.js:64:7
    at new Promise (<anonymous>)
    at middleware (/node_modules/webpack-dev-middleware/lib/middleware.js:63:12)
    at /node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/karma.js:270:13
    at call (/node_modules/connect/index.js:239:7)
    at next (/node_modules/connect/index.js:183:5)
    at /node_modules/karma/lib/web-server.js:24:9
    at call (/node_modules/connect/index.js:239:7)
    at next (/node_modules/connect/index.js:183:5)
    at nullProxy (/node_modules/karma/lib/middleware/proxy.js:86:52)
    at call (/node_modules/connect/index.js:239:7)
    at next (/node_modules/connect/index.js:183:5)

@wvankuipers

@devoto13

Thanks for the link @wvankuipers. It is indeed a change in behaviour in Node, which lead to a crash of Angular CLI (because of this line).

It looks like Node is going to revert this change in LTS line. So below is the information for people experiencing this issue:

  1. Avoid affected Node version 14.15.2. And avoid 15.x as it is unsupported by both Karma and Angular CLI at the moment.
  2. Subscribe to ng test crashes on Node 14.15.2 and Node 15 angular/angular-cli#19644 for updates on Node 15 support in regards of this issue.

@devoto13
devoto13

changed the title
Karma test cases breaking in node 14.15.2

UnhandledRejection: Cannot read property ‘range’ of undefined

Dec 17, 2020

This was referenced

Dec 17, 2020

@devoto13

@johnjbarton I think we should keep this pinned until fix is released in the next Node version, so people can easily find it and don’t open new issues about the same problem.

@johnjbarton

Ok thanks. Did not know this pinned thing 😉

@Mayur123-mg

  • i also check with Angular CLI @11.x and node v14.15.2 test case run there is no issue in it
  • who want to use node v14.15.2 for angular please update your angular version
  • use command ng update in your angular setup

@johnjbarton

@rattkin

still happening on v14.15.3

@devoto13

@rattkin I can’t reproduce on Node 14.15.3 using test project from #3588 (comment). Please double check that you use the mentioned Node version and provide the minimal project producing the error if you still believe that this is a bug.

@rattkin

@devoto13 I upgraded Triton to latest and it is fixed now. Sorry for mistake, the environment that had the problem was not on 14.15.3.
solved.

@TeaTimeForever

Same issue appeared again starting from node v15.0.0

@devoto13

@mx2s

downgrading from node v15 to v14.16.0 helped, tests are working now

@myu-1987

«UnhandledRejection» because Karma Runner is not compatible with Node Version 15. You have to downgrade your node version below or equal to 14.

Karma Runner Open Issue — #3571

the form response sheet
This is what I have written in Script editor so as to auto-apply a formula to a new added row when a new response is submitted on the Google Forms linked to my spreadsheet. First I was using onFormSubmit(e) function without creating an event object, resulting the error:TypeError: Cannot read property 'range' of undefined at onFormSubmit. then, as suggested, I created the event object onFormSubmitEvent() but still the very error is occurring.As you can see in photo, the first column and the first 5 rows are not used for the Form responses. the 4th row shows form questions, 5th row just column numbers, from 6th row the responses are collected(may this also be one of the reasons?). Please help to solve the problem.

function onFormSubmitEvent() {
  var dataRange = SpreadsheetApp.getActiveSheet().getDataRange();
  var data = dataRange.getValues();
  var headers = data[0];
  for (var row=1; row < data.length; row++) {
    var e = {};
    e.values = data[row].filter(Boolean);
    e.range = dataRange.offset(row,0,1,data[0].length);
    e.namedValues = {};

    for (var col=0; col<headers.length; col++) {
      e.namedValues[headers[col]] = [data[row][col]];
    }

    onFormSubmit(e);
  }
}


function onFormSubmit(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var range = e.range;
  var row1 = range.getRow();
  var sheet = range.getSheet();

  sheet.getRange(row,17).setFormula("=if($O"+row+"="UZS",index(googlefinance("currency:UZSUSD","price",$B"+row+"),2,2)*$P"+row+",if($O"+row+"="EUR",index(googlefinance("currency:EURUSD","price",$B"+row+"),2,2)*$P"+row+",$P"+row+"))");

При отладке своего кода (обычно на JavaScript) программист может столкнуться с системным сообщением об ошибке «TypeError: Cannot read property ‘xxx’ of undefined». Вместо значения ХХХ указана какая-либо объявленная переменная или свойство объекта, значение которых по различным причинам не задано разработчиком. Ниже разберём, каков перевод данного сообщения, и каково может быть решение возникшей проблемы.

Ошибка TypeError

Содержание

  1. Почему возникает ошибка
  2. Присвойте начальное значение переменной
  3. Улучшите связность вашего кода
  4. Проверьте наличие свойства
  5. Деструктурируйте доступ к свойствам нужного объекта
  6. Заключение

Почему возникает ошибка

В переводе данное сообщение выглядит как «Ошибка типа: Не удаётся прочитать неопределённое свойство ХХХ». Поскольку в некоторых языках программирования (в частности, «JavaScript») есть возможность получения доступа к неинициализированным значениям, то это может вызывать появление рассматриваемой мной ошибки.

Что до причин ошибки undefined, то она обычно возникает при отладке какого-либо программного кода, и может быть вызвана следующими факторами:

  • Использующиеся в программном коде переменная не была инициализирована (переменной не присвоено значение);
  • Была осуществлена попытка доступа к отсутствующему свойству объекта;
  • Была попытка получить доступ к отсутствующему элементу массива.

Давайте разберёмся, как исправить данную ошибку при написании вашего кода.

Фото реппера и слов об ошибке

Читайте также: Failed to execute ‘replaceChild’ on ‘Node’  на JavaScript – как исправить.

Присвойте начальное значение переменной

Наиболее очевидным способом исправить ошибку «TypeError: Cannot read property ‘xxx’ of undefined» является присвоение переменной начального значения. Чем меньше такая переменная пребывает в неинициализированном состоянии – тем будет лучше. В идеале лучше сразу же присвоить значение «Variable» = «начальное значение» (‘initial’), хотя далеко не всегда специфика вашего кода может предполагать указанный вариант.

Улучшите связность вашего кода

Термин «связность» в нашем контексте характеризует уровень взаимосвязанности элементов разрабатываемого вами модуля (пространства имён, метода, класса, блока кода). Как известно, существуют два типа связности, а именно сильная и слабая связность. Использование сильной связности предполагает фокусировку элементов модуля лишь на одной задаче. Потому для извлечения выгоды из сильной связности, необходимо держать используемые переменные поближе к блоку кода, в работе которого они используются.

К примеру, вместо блока кода:

Блок кода

будет оптимальнее переместить переменные поближе к месту их применения:

Конечный блок кода

Улучшение связности позволит избежать появление ошибки «Cannot read property ‘xxx’ of undefined» при отладке вашего кода.

Проверьте наличие свойства

В языке Javascript имеются ряд инструментов, позволяющих определить, имеет ли необходимый нам объект какое-либо свойство:

В частности, это:

  • typeof obj.prop !== ‘undefined’ — данный инструмент позволяет проверить тип значения свойства;
  • obj.prop !== undefined — этот инструмент позволяет сравнить объект непосредственно с undefined;
  • ‘prop’ in obj позволяет проверить объект на наличие его собственного или полученного свойства;
  • И obj.hasOwnProperty(‘prop’) позволяет проверить объект на наличие его собственного свойства.

В этом и схожих случаях рекомендуется использовать оператор in, который обладает простым и удобным синтаксисом. Наличие оператора in демонстрирует желание проверить, имеет ли объект нужное свойство без обращения к фактическому значению данного свойства.

Деструктурируйте доступ к свойствам нужного объекта

Деструктурирование нужного объекта позволяет непосредственно извлекать значения свойства объекта в переменные или, если такое свойство не существует, устанавливать значение по дефаулту. Такой вариант позволяет исключить прямой контакт с undefined.

Извлечение свойств теперь выглядит примерно так:

программный код

Деструктурирование хорошо, когда можно указать значение по умолчанию, и это значение будет возвращено при попытке доступа к отсутствующему свойству. В конечном счёте, благодаря деструктурированию вы сможете избежать появления undefined и всех сопутствующих проблем.

Это интересно: что означает «JavaScript error: Mutations are not initialized.

Заключение

В нашей статье мы разобрали, почему появляется ошибка «TypeError: Cannot read property ‘xxx’ of undefined», как она переводится и как от неё можно избавиться. Во избежание возникновения данной ошибки присвойте начальное значение соответствующей переменной. Это позволит избежать появления рассмотренной выше дисфункции при отладке вашего кода.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка tpm device is not detected
  • Ошибка txtsetup sif поврежден