При отладке своего кода (обычно на JavaScript) программист может столкнуться с системным сообщением об ошибке «TypeError: Cannot read property ‘xxx’ of undefined». Вместо значения ХХХ указана какая-либо объявленная переменная или свойство объекта, значение которых по различным причинам не задано разработчиком. Ниже разберём, каков перевод данного сообщения, и каково может быть решение возникшей проблемы.
Содержание
- Почему возникает ошибка
- Присвойте начальное значение переменной
- Улучшите связность вашего кода
- Проверьте наличие свойства
- Деструктурируйте доступ к свойствам нужного объекта
- Заключение
Почему возникает ошибка
В переводе данное сообщение выглядит как «Ошибка типа: Не удаётся прочитать неопределённое свойство ХХХ». Поскольку в некоторых языках программирования (в частности, «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», как она переводится и как от неё можно избавиться. Во избежание возникновения данной ошибки присвойте начальное значение соответствующей переменной. Это позволит избежать появления рассмотренной выше дисфункции при отладке вашего кода.
Hi
Having some issues with autoUpdate.
It find’s the update but before it’s going to download the update it gives me a error
TypeError: Cannot read property ‘url’ of undefined
cant find out why it’s giving me this error
Version:
electron-updater = 2.16.1
electron = 1.7.9
electron-builder = 19.46.9
package.json
{
"name": "Wired",
"version": "0.1.0",
"description": "Home assistant",
"repository": {
"type": "git",
"url": "https://github.com/andrewo0/wired.git"
},
"scripts": {
"postinstall": "install-app-deps"
},
"dependencies": {
"electron-updater": "^2.16.1",
"electron-log": "^1.3.0"
},
"devDependencies": {
"electron-builder": "19.46.9",
"electron-updater": "^2.16.1",
"electron": "1.7.9",
"gulp": "^3.9.1",
"mocha": "^4.0.1",
"spectron": "^3.7.2",
"webpack-stream": "^3.2.0"
},
"build": {
"appId": "com.electron.wired",
"publish": [
{
"provider": "github",
"owner": "andrewo0",
"private": true
}
],
"win": {
"target": "nsis"
},
"nsis": {
"oneClick": false,
"perMachine": false,
"allowToChangeInstallationDirectory": true
},
"mac": {
"category": "your.app.category.type"
}
}
}
index.js
const {app, BrowserWindow, Menu, protocol, ipcMain} = require('electron');
const log = require('electron-log');
const {autoUpdater} = require("electron-updater");
let window;
let path;
let json;
path = require('path');
json = require('settings.json');
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = 'info';
log.info('App starting...');
function sendStatusToWindow(text) {
log.info(text);
window.webContents.send('message', text);
}
function mainWindow(){
window = new BrowserWindow({
title: json.name,
width: json.settings.width,
height: json.settings.height,
frame: json.settings.frame,
titleBarStyle: json.settings.titlebarstyle,
backgroundColor: '#000000',
show: false
});
window.loadURL('file://' + path.join(__dirname, '..', '..') + '/index.html#v' + app.getVersion());
window.once('ready-to-show', () => {
window.show()
})
window.on('closed', function () {
window = null;
});
return window;
}
app.on('ready', function() {
autoUpdater.checkForUpdates();
});
autoUpdater.on('checking-for-update', () => {
sendStatusToWindow('Checking for update...');
})
autoUpdater.on('update-available', (info) => {
sendStatusToWindow('Update available.');
})
autoUpdater.on('update-not-available', (info) => {
sendStatusToWindow('Update not available.');
})
autoUpdater.on('error', (err) => {
sendStatusToWindow('Error in auto-updater. ' + err);
})
autoUpdater.on('download-progress', (progressObj) => {
let log_message = "Download speed: " + progressObj.bytesPerSecond;
log_message = log_message + ' - Downloaded ' + progressObj.percent + '%';
log_message = log_message + ' (' + progressObj.transferred + "/" + progressObj.total + ')';
sendStatusToWindow(log_message);
})
autoUpdater.on('update-downloaded', (info) => {
sendStatusToWindow('Update downloaded');
});
app.on('ready', function () {
mainWindow();
});
app.on('window-all-closed', () => {
app.quit();
});
Log:
[2017-11-30 09:38:00:0536] [info] App starting...
[2017-11-30 09:38:00:0607] [info] Checking for update
[2017-11-30 09:38:00:0607] [info] Checking for update...
[2017-11-30 09:38:01:0926] [info] Generated new staging user ID:
[2017-11-30 09:38:03:0907] [info] Found version 0.1.1 (url: Wired-Setup-0.1.1.exe)
[2017-11-30 09:38:03:0907] [info] Update available.
[2017-11-30 09:38:03:0908] [info] Downloading update from Wired-Setup-0.1.1.exe
[2017-11-30 09:38:03:0912] [error] Error: TypeError: Cannot read property 'url' of undefined
at updateInfo.files.map.it (C:UsersAndrewAppDataLocalProgramsWiredresourcesapp.asarnode_moduleselectron-updatersrcPrivateGitHubProvider.ts:101:63)
at Array.map (native)
at PrivateGitHubProvider.resolveFiles (C:UsersAndrewAppDataLocalProgramsWiredresourcesapp.asarnode_moduleselectron-updatersrcPrivateGitHubProvider.ts:98:29)
at C:UsersAndrewAppDataLocalProgramsWiredresourcesapp.asarnode_moduleselectron-updatersrcNsisUpdater.ts:19:53
From previous event:
at NsisUpdater.doDownloadUpdate (C:UsersAndrewAppDataLocalProgramsWiredresourcesapp.asarnode_moduleselectron-updateroutNsisUpdater.js:133:11)
at C:UsersAndrewAppDataLocalProgramsWiredresourcesapp.asarnode_moduleselectron-updatersrcAppUpdater.ts:304:25
at Generator.next (<anonymous>)
From previous event:
at NsisUpdater.downloadUpdate (C:UsersAndrewAppDataLocalProgramsWiredresourcesapp.asarnode_moduleselectron-updateroutAppUpdater.js:355:11)
at C:UsersAndrewAppDataLocalProgramsWiredresourcesapp.asarnode_moduleselectron-updatersrcAppUpdater.ts:280:49
From previous event:
at NsisUpdater.doCheckForUpdates (C:UsersAndrewAppDataLocalProgramsWiredresourcesapp.asarnode_moduleselectron-updateroutAppUpdater.js:326:11)
at C:UsersAndrewAppDataLocalProgramsWiredresourcesapp.asarnode_moduleselectron-updatersrcAppUpdater.ts:228:25
at Generator.next (<anonymous>)
at runCallback (timers.js:672:20)
at tryOnImmediate (timers.js:645:5)
at processImmediate [as _immediateCallback] (timers.js:617:5)
From previous event:
at NsisUpdater._checkForUpdates (C:UsersAndrewAppDataLocalProgramsWiredresourcesapp.asarnode_moduleselectron-updateroutAppUpdater.js:280:11)
at NsisUpdater.checkForUpdates (C:UsersAndrewAppDataLocalProgramsWiredresourcesapp.asarnode_moduleselectron-updatersrcAppUpdater.ts:177:35)
at App.<anonymous> (C:UsersAndrewAppDataLocalProgramsWiredresourcesapp.asarjavascriptsmainindex.js:45:15)
at emitTwo (events.js:111:20)
at App.emit (events.js:194:7)
[2017-11-30 09:38:03:0912] [info] Error in auto-updater. TypeError: Cannot read property 'url' of undefined
Can someone help with this? I got the file AddPost.js
</div>
{this.props.admin.post.PostImage ?
<img src={API.makeFileURL(this.props.admin.post.PostImage[0].url, this.props.auth.token)} className="post-image" />
: null}
<div>
<Button
variant="contained"
color="primary"
onClick={e => {
$('.MyFile').trigger('click');
}}
><ImageIcon />Upload Post Image</Button>
<input type="file" style={{display: 'none'}} className="MyFile" onChange={this.uploadImage}/>
</div>
And API file contains this function:
makeFileURL: (url, token) => {
return host + url + "?access_token" + token;
}
asked Nov 6, 2019 at 20:29
1
import {Link,Route} from 'react-router-dom';
export const Category = ({match}) => {
return (
<div>
<ul>
<li><Link to={`${match.url}/mobile`} >Mobile</Link></li>
<li><Link to={`${match.url}/laptop`} >Laptop</Link></li>
<li><Link to={`${match.url}/shoes`} >Shoes</Link></li>
</ul>
</div>
)
}
In this case any one have get error «TypeError: Cannot read property ‘url’ of undefined»
so need to change
<Route path='/category' component={Category} />
greg-449
108k230 gold badges104 silver badges144 bronze badges
answered Apr 23, 2021 at 6:42
1
What do this.props.admin.post and this.props.admin.post.PostImage evaluate to? I’d start with console.log‘ing those out and making sure that it returns an array of objects that have a url property
answered Nov 6, 2019 at 21:49
Try this one
this.props.admin.post.PostImage&&
this.props.admin.post.PostImage[0]&&
this.props.admin.post.PostImage[0].url
answered Apr 23, 2021 at 6:47
Если при подписании на сайте ЕИС (ЕРУЗ) https://zakupki.gov.ru/ возникает ошибка «Cannot read properties of undefined (reading ‘CreateObjectAsync’)», мы рекомендуем в первую очередь использовать браузер Chromium GOST, так как ЕИС корректно работает именно в нём. Если вы планируете работать в Яндекс.Браузере — необходимо выполнить дополнительные настройки.
Если вы хотите использовать другой браузер, в котором возникает эта ошибка — рекомендуем обратиться в техническую поддержку ЕИС для уточнения сроков исправления ошибки в нужном для вас браузере.
Настройте для работы браузер Chromium GOST
1. Установите браузер:
- Автоматически с нашего Веб-диска. После установки переходите к пункту 2 инструкции.
- Вручную по ссылке https://github.com/deemru/Chromium-Gost/releases/. На открывшейся странице выберите версию браузера, которая соответствует разрядности вашей операционной системы, разрядность вашей системы можно определить следующими способами:
а) Нажать правой кнопкой мыши на Мой компьютер — Свойства.
б) Нажать комбинацию клавиш Win+Pause.
в) Нажать правой кнопкой мыши на Пуск — Система.
г) Воспользоваться инструкцией от Microsoft.
Запустите скачанный файл и следуйте подсказкам на экране для установки
2. Запустите браузер Chromium GOST и откройте в нём ссылку https://chrome.google.com/webstore/detail/cryptopro-extension-for-c/iifchhfnnmpdbibifmljnfjhpififfog. Проверьте, что расширение с открывшейся страницы установлено (должна отобразиться кнопка «Удалить из Chrome»):
Если вы видите кнопку «Установить» — нажмите её для установки расширения:
3. Повторите подписание документов в ЕИС
Настроить для работы Яндекс.Браузер
1. Скачайте браузер по ссылке https://browser.yandex.ru/ . Если Яндекс.Браузер уже установлен и ранее ЕИС (ЕРУЗ) работал в нём корректно, то переходите к пункту 4.
2. В Яндекс.Браузере зайдите в раздел «Настройки» — «Системные», либо откройте в нем ссылку: browser://settings/system
Включите настройку «Подключаться к сайтам, использующим шифрование по ГОСТ. Требуется КриптоПро»:
3. Установите расширение https://chrome.google.com/webstore/detail/cryptopro-extension-for-c/iifchhfnnmpdbibifmljnfjhpififfog так же, как это описано ранее в инструкции про Chromium GOST.
4. Повторите подписание в ЕИС. Если ошибка сохранилась, для нормальной работы портала в Яндекс.Браузере нужно выключить расширение из каталога Opera:
Откройте «Настройки» — «Дополнения», либо откройте в браузере ссылку browser://tune/
Отключите расширение Каталог КриптоПро ЭЦП переведя ползунок в левое положение:
Внимание! Изменение этой настройки может негативно повлиять работу на некоторых сайтах, например на www.sberbank-ast.ru, www.rts-tender.ru и https://etp.gpb.ru/ . Решение об отключении вы принимаете самостоятельно!
Перезапустите браузер и повторите подписание в ЕИС.
Допустим, вы делаете страницу с формой и полем ввода:
<form name="myform">
<input name="myinput" value="10" />
</form>
Нужно, чтобы скрипт нашёл эту форму, достал из неё значение поля ввода и вывел его на экран. Вы пишете скрипт и оформляете его как отдельный файл, который подключаете в разделе head:
<script>
var str = '';
for(i=0; i < document.myform.elements.length; i++){
str += document.myform.elements[i].name +
'=' + encodeURIComponent(document.myform.elements[i].value) +
(i == document.myform.elements.length -1 ? '' : '&');
}
alert(str);
</script>
Этот скрипт должен быть правильным. При тестировании внутри консоли он делает именно то, что нужно. Но после запуска скрипт падает с ошибкой:
❌ Uncaught TypeError: Cannot read property
Это означает: «Вы пытаетесь прочитать у объекта какое-то свойство, но я не могу его найти, а значит, не могу и прочитать то, чего нет».
Странно, ведь вы уверены, что у этого объекта такое свойство точно есть, и вы сто раз так уже делали.
Всё так и одновременно не так.
Что делать с ошибкой Uncaught TypeError: Cannot read property
Эта ошибка чаще всего происходит, когда вы обращаетесь к свойствам объекта раньше, чем объект готов:
- Скорее всего, объект ещё не загрузился.
- Может быть, этот объект должен появиться на странице по скрипту, который ещё не выполнился.
- Допущена опечатка в названии объекта, поэтому при обращении к нему скрипт его не находит.
Наш случай — первый и самый распространённый: мы вызываем скрипт в разделе <head>, но форма у нас ещё не готова — она банально не загружена в документ, поэтому скрипт не может прочитать свойства несуществующей формы.
Чтобы избавиться от этой ошибки, нужно добавить в вызов скрипта атрибут defer — он заставит скрипт подождать, пока страница загрузится полностью, вместе с формой.
<script defer src="...">
Второй вариант — поместить вызов скрипта сразу после формы, тогда к моменту вызова всё окажется на своих местах и ошибки не будет. Или вообще в конце всего документа.
Getting this error when running server.js.
Started http server.
info - socket.io started
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Cannot read property 'url' of undefined
at Function.handle (/opt/lampp/htdocs/notifications/sites/all/modules/nodejs/node_modules/express/node_modules/connect/lib/proto.js:105:18)
at Server.app (/opt/lampp/htdocs/notifications/sites/all/modules/nodejs/node_modules/express/node_modules/connect/lib/connect.js:60:31)
at Server.serverListening (/opt/lampp/htdocs/notifications/sites/all/modules/nodejs/node_modules/socket.io/node_modules/policyfile/lib/server.js:136:16)
at Server.g (events.js:156:14)
at Server.emit (events.js:64:17)
at Array.0 (net.js:777:10)
at EventEmitter._tickCallback (node.js:192:40)
This is the output of npm install
require@0.4.9 ./node_modules/require
└── uglify-js@1.0.3
express@3.0.0alpha1 ./node_modules/express
├── mime@1.2.5
├── commander@0.5.2
├── mkdirp@0.3.1
├── debug@0.6.0
└── connect@2.1.2
socket.io@0.9.6 ./node_modules/socket.io
├── policyfile@0.0.4
├── redis@0.6.7
└── socket.io-client@0.9.6
And this is my config file:
backendSettings = {
"scheme":"http",
"host":"localhost",
"port":8080,
"resource":"/socket.io",
"publishUrl":"/notifications/nodejs/publish",
"serviceKey":"54468779wifjo78fjwijowef",
"backend":{
"port":80,
"host":"localhost",
"messagePath":"/nodejs/message"
},
"clientsCanWriteToChannels":false,
"clientsCanWriteToClients":false,
"extensions":"",
"debug":true,
"transports":["websocket",
"flashsocket",
"htmlfile",
"xhr-polling",
"jsonp-polling"],
"jsMinification":true,
"jsEtag":true,
"logLevel":1};
Thanks in advance
The “cannot read property of undefined” error occurs when you attempt to access a property or method of a variable that is undefined. You can fix it by adding an undefined check on the variable before accessing it.
Depending on your scenario, doing any one of the following might resolve the error:
- Add an
undefinedcheck on the variable before accessing it. - Access the property/method on a replacement for the
undefinedvariable. - Use a fallback result instead of accessing the property.
- Check your code to find out why the variable is
undefined.
1. Add undefined check on variable
To fix the “cannot read property of undefined” error, check that the value is not undefined before accessing the property.
For example, in this code:
const auth = undefined;
console.log(auth); // undefined
// ❌ TypeError: Cannot read properties of undefined (reading 'user')
console.log(auth.user.name);
We can fix the error by adding an optional chaining operator (?.) on the variable before accessing a property. If the variable is undefined or null, the operator will return undefined immediately and prevent the property access.
const auth = undefined;
console.log(auth); // undefined
// ✅ No error
console.log(auth?.user?.name); // undefined
The optional chaining operator also works when using bracket notation for property access:
const auth = undefined;
console.log(auth); // undefined
// ✅ No error
console.log(auth?.['user']?.['name']); // undefined
This means that we can use it on arrays:
const arr = undefined;
console.log(arr?.[0]); // undefined
// Array containing an object
console.log(arr?.[2]?.prop); // undefined
Note
Before the optional chaining was available, the only way to avoid this error was to manually check for the truthiness of every containing object of the property in the nested hierarchy, i.e.:
const a = undefined;
// Optional chaining
if (a?.b?.c?.d?.e) {
console.log(`e: ${e}`);
}
// No optional chaining
if (a && a.b && a.b.c && a.b.c.d && a.b.c.d.e) {
console.log(`e: ${e}`);
}
2. Use replacement for undefined variable
In the first approach, we don’t access the property or method when the variable turns out to be undefined. In this solution, we provide a fallback value that we’ll access the property or method on.
For example:
const str = undefined;
const result = (str ?? 'old str').replace('old', 'new');
console.log(result); // 'new str'
The null coalescing operator (??) returns the value to its left if it is not null or undefined. If it is, then ?? returns the value to its right.
console.log(5 ?? 10); // 5
console.log(undefined ?? 10); // 10
The logical OR (||) operator can also do this:
console.log(5 || 10); // 5
console.log(undefined || 10); // 10
3. Use fallback value instead of accessing property
Another way to solve the “cannot read property of undefined” error is to avoid the property access altogether when the variable is undefined and use a default fallback value instead.
We can do this by combining the optional chaining operator (?.) and the nullish coalescing operator (??).
For example:
const arr = undefined;
// Using "0" as a fallback value
const arrLength = arr?.length ?? 0;
console.log(arrLength); // 0
const str = undefined;
// Using "0" as a fallback value
const strLength = str?.length ?? 0;
console.log(strLength); // 0
4. Find out why the variable is undefined
The solutions above are handy when we don’t know beforehand if the variable will be undefined or not. But there are situations where the “cannot read property of undefined” error is caused by a coding error that led to the variable being undefined.
It could be that you forgot to initialize the variable:
let doubles;
let nums = [1, 2, 3, 4, 5];
for (const num of nums) {
let double = num * 2;
// ❌ TypeError: cannot read properties of undefined (reading 'push')
doubles.push(double);
}
console.log(doubles);
In this example, we call the push() method on the doubles variable without first initializing it.
let doubles;
console.log(doubles); // undefined
Because an uninitialized variable has a default value of undefined in JavaScript, accessing a property/method causes the error to be thrown.
The obvious fix for the error, in this case, is to assign the variable to a defined value.
// ✅ "doubles" initialized before use
let doubles = [];
let nums = [1, 2, 3, 4, 5];
for (const num of nums) {
let double = num * 2;
// push() called - no error thrown
doubles.push(double);
}
console.log(doubles); // [ 2, 4, 6, 8, 10 ]
Another common mistake that causes this error is accessing an element from an array variable before accessing an Array property/method, instead of accessing the property/method on the actual array variable.
const array = [];
// ❌ TypeError: Cannot read properties of undefined (reading 'push')
array[0].push('html');
array[0].push('css');
array[0].push('javascript');
console.log(array);
Accessing the 0 property with bracket indexing gives us the element at index 0 of the array. The array has no element, so arr[0] evaluates to undefined and calling push() on it causes the error.
To fix this, we need to call the method on the array variable, not one of its elements.
const array = [];
// ✅ Call push() on "array" variable, not "array[0]"
array.push('html');
array.push('css');
array.push('javascript');
console.log(array); // [ 'html', 'css', 'javascript' ]
Conclusion
In this article, we saw some helpful ways of resolving the “cannot read property of undefined” error in JavaScript. They might not resolve the error totally in your case, but they should assist you during your debugging.
Every Crazy Thing JavaScript Does
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.
Sign up and receive a free copy immediately.
Ayibatari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.






.png)
.png)
.png)
.png)
.png)
.png)
.png)

