Ошибка cannot read properties of undefined reading call

I'm having an issue with webpack where if I stop watching and restart, it will build just fine, but if I edit a file and save it, the incremental build fails with this error: Uncaught TypeError...

I can confirm this is still an issue.

I am using webpack 5.30 and vue 2.6.11

I am trying to implement lazy loading on our already existing vue app to reduce our bundle size. Here is how I am importing the component:

const ManageSupport = () => import(/* webpackChunkName: "view-support" */ 'components/helpdesk/view-support')

The chunk is created successfully, based on this webpack output: asset view-support.js 29.4 KiB [emitted] (name: view-support)

When trying to navigate to that route, I keep getting (consistently) the error
`[vue-router] Failed to resolve async component default: TypeError: Cannot read property ‘call’ of undefined

TypeError: Cannot read property ‘call’ of undefined
at webpack_require (main.js:26989)
at Function.fn (main.js:27159)`

A snippet from main.js where the error is thrown:

// Execute the module function
/******/ 		try {
/******/ 			var execOptions = { id: moduleId, module: module, factory: __webpack_modules__[moduleId], require: __webpack_require__ };
/******/ 			__webpack_require__.i.forEach(function(handler) { handler(execOptions); });
/******/ 			module = execOptions.module;
/******/ (error here)execOptions.factory.call(module.exports, module, module.exports, execOptions.require);
/******/ 		} catch(e) {
/******/ 			module.error = e;
/******/ 			throw e;
/******/ 		}

My webpack configuration:

const webpack = require('webpack');
const { VueLoaderPlugin } = require("vue-loader")
const TerserPlugin = require("terser-webpack-plugin")
const CompressionPlugin = require('compression-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
var FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin')

const bundleOutputDir = './wwwroot/dist';

module.exports = (env) => {
    const isDevBuild = env.prod != 'true';
    console.log("Starting webpack " + (isDevBuild ? "Dev" : "Prod") + " Build (main.js)")
    return {
        mode: isDevBuild ? 'development' : 'production',
        target: isDevBuild ? false : ['web', 'es5'],
        entry: './ClientApp/boot-app.js',
        output: {
            path: path.resolve(__dirname, bundleOutputDir),
            filename: '[name].js',
            publicPath: '/dist/'
        },
        resolve: {
            alias: {
                'vue$': 'vue/dist/vue',
                'components': path.resolve(__dirname, './ClientApp/components'),
                'views': path.resolve(__dirname, './ClientApp/views'),
                'utils': path.resolve(__dirname, './ClientApp/utils')
            },
            extensions: ["*", ".js", ".vue", ".json"]
        },
        module: {
            rules: [
                // Vue
                { test: /.vue$/, loader: "vue-loader", exclude: /node_modules/ },

                // CSS
                { test: /.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader'] },

                {
                    test: /.m?js/,
                    resolve: {
                        fullySpecified: false
                    }
                },

                // JavaScript
                {
                    test: /.js$/, exclude: /node_modules/, loader: 'babel-loader',
                    exclude: file => (
                        /node_modules/.test(file) &&
                        !/.vue.js/.test(file)
                    )
                },

                { test: /.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
            ],
        },
        plugins: [

            new MiniCssExtractPlugin({ filename: "site.css" }),

            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: path.join(__dirname, 'wwwroot', 'dist', 'vendor-manifest.json')
            }),

            new VueLoaderPlugin(),

            new FriendlyErrorsWebpackPlugin(),

        ].concat(
            isDevBuild ? [

                // Dev-only dependencies

            ] : [

                    // Prod-only dependencies

                    new CompressionPlugin({
                        filename: '[path][base]',
                        test: /.(js|css|svg|json)$/,
                        deleteOriginalAssets: true
                    })

                ]),
        optimization: isDevBuild ? {} : {
            minimize: true,
            minimizer: [new TerserPlugin({
                test: /.js(?.*)?$/i,
            })]
        },
        cache: true
    }
}

My package.json

{
    "scripts": {
        "build": "cross-env webpack --progress --no-devtool --config webpack.config.js --env prod=true",
        "start": "NODE_OPTIONS=--max_old_space_size=4096 webpack serve --progress --hot --hot-only --config webpack.config.js --content-base 'wwwroot' --env prod=false",
        "vendor": "webpack --config webpack.config.vendor.js --env prod=false --progress --stats-error-details",
        "app": "cross-env NODE_OPTIONS=--max_old_space_size=4096 webpack --progress --config webpack.config.js --env prod=false",
        "help": "webpack --help"
    },
    "dependencies": {
        "@babel/plugin-transform-runtime": "^7.13.10",
        "@fortawesome/fontawesome-svg-core": "^1.2.28",
        "@fortawesome/free-brands-svg-icons": "^5.13.0",
        "@fortawesome/pro-light-svg-icons": "^5.13.0",
        "@fortawesome/pro-regular-svg-icons": "^5.13.0",
        "@fortawesome/pro-solid-svg-icons": "^5.13.0",
        "@fortawesome/vue-fontawesome": "^0.1.9",
        "@microsoft/signalr": "=3.1.6",
        "axios": "^0.21.1",
        "core-js": "^2.6.11",
        "epsg-index": "^1.0.0",
        "font-awesome": "^4.6.3",
        "lodash": "^4.17.19",
        "moment": "^2.24.0",
        "moment-mini": "^2.24.0",
        "vue": "^2.6.11",
        "vue-router": "^2.1.1",
        "vue-template-compiler": "^2.6.11",
        "vuex": "^2.1.1",
        "vuex-persistedstate": "^2.5.4",
        "vuex-router-sync": "^4.0.1"
    },
    "devDependencies": {
        "@babel/core": "^7.13.14",
        "@babel/plugin-proposal-class-properties": "^7.13.0",
        "@babel/preset-env": "^7.13.12",
        "babel-loader": "^8.2.2",
        "bootstrap": "^3.3.6",
        "compression-webpack-plugin": "^7.1.2",
        "cross-env": "^3.1.3",
        "css-loader": "^5.2.1",
        "event-source-polyfill": "^0.0.7",
        "friendly-errors-webpack-plugin": "^1.7.0",
        "file-loader": "^6.2.0",
        "html-webpack-plugin": "^5.3.1",
        "jquery": "^2.2.1",
        "lodash-webpack-plugin": "^0.11.5",
        "mini-css-extract-plugin": "^1.4.1",
        "optimize-css-assets-webpack-plugin": "^5.0.4",
        "postcss-loader": "^5.2.0",
        "postcss-preset-env": "^6.7.0",
        "scope-loader": "^1.0.3",
        "spectacle-docs": "^1.0.7",
        "style-loader": "^2.0.0",
        "url-loader": "^0.5.7",
        "vue-loader": "^15.9.6",
        "webpack": "^5.30.0",
        "webpack-cli": "^4.6.0",
        "webpack-dev-server": "^3.11.2",
        "webpack-hot-middleware": "^2.12.2"
    }
}

The TypeError: Cannot read property of undefined is one of the most common type errors in JavaScript. It occurs when a property is read or a function is called on an undefined variable.

Install the JavaScript SDK to identify and fix these undefined errors

Error message:

TypeError: Cannot read properties of undefined (reading x)

Error type:

TypeError

What Causes TypeError: Cannot Read Property of Undefined

Undefined means that a variable has been declared but has not been assigned a value.

In JavaScript, properties and functions can only belong to objects. Since undefined is not an object type, calling a function or a property on such a variable causes the TypeError: Cannot read property of undefined.

TypeError: Cannot Read Property of Undefined Example

Here’s an example of a JavaScript TypeError: Cannot read property of undefined thrown when a property is attempted to be read on an undefined variable:

function myFunc(a) {
console.log(a.b);
}

var myVar;
myFunc(myVar);

Since the variable myVar is declared but not initialized, it is undefined. When it is passed to the myFunc function, the property b is attempted to be accessed. Since a is undefined at that point, running the code causes the following error:

TypeError: Cannot read properties of undefined (reading 'b')

How to Avoid TypeError: Cannot Read Property of Undefined

When such an error is encountered, it should be ensured that the variable causing the error is assigned a value:

function myFunc(a) {
    console.log(a.b);
}

var myVar = {
    b: 'myProperty'
};

myFunc(myVar);

In the above example, the myVar variable is initialized as an object with a property b that is a string. The above code runs successfully and produces the following output on the browser console:

myProperty

To avoid coming across situations where undefined variables may be accessed accidentally, an if check should be added before dealing with such variables:

if (myVar !== undefined) {
    ...
}

if (typeof(myVar) !== 'undefined') {
    ...
}

Updating the previous example to include an if check:

function myFunc(a) {
    if (a !== undefined) {
        console.log(a.b);
    }
}

var myVar;
myFunc(myVar);

Running the above code avoids the error since the property b is only accessed if a is not undefined.

Here is how you can handle errors using a try { } catch (e) { } block.

// Caught errors
try {

  //Place your code inside this try, catch block
  //Any error can now be caught and managed

} catch (e) {
  Rollbar.error("Something went wrong", e);
  console.log("Something went wrong", e);
}

Here is how you can setup a JavaScript Error handler: Setup JavaScript Error Handler

Where TypeError Resides in the JavaScript Exception Hierarchy

JavaScript provides a number of core objects that allow for simple exception and error management. Error handling is typically done through the generic Error object or from a number of built-in core error objects, shown below:

  • Error
  • InternalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
    • Cannot read property of undefined

As seen from the hierarchy above, TypeError is a built-in JavaScript error object that allows for the administration of such errors. The “Cannot read property of undefined” TypeError is a descendant of the TypeError object.

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing JavaScript errors easier than ever. Sign Up Today!

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.

The "cannot read property of undefined" error in JavaScript.

Depending on your scenario, doing any one of the following might resolve the error:

  1. Add an undefined check on the variable before accessing it.
  2. Access the property/method on a replacement for the undefined variable.
  3. Use a fallback result instead of accessing the property.
  4. 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.

Every Crazy Thing JavaScript Does

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.

“Cannot read properties of undefined in JavaScript” means JavaScript cannot read the properties of an object that you have not defined before. Let’s follow the article below to figure out how to solve this problem.

Common causes of the error “cannot read properties of undefined” in JavaScript

There are many causes of this problem, but the main cause is that JS can’t read the property of the object that stores the undefined value or the object is uninitialized.

Some cases cause this error:

  1. You are accessing an object that has an undefined data type or has not been assigned a value.

Example:

let nothing = undefined;
console.log(nothing.name);

Output:

Error: Cannot read properties of undefined (reading 'name')
  1. You are trying to call a method in the undefined object.

Example:

let nothing;
console.log(nothing.toString());

Output:

Error: Cannot read properties of undefined (reading 'toString')

Solutions for this error

Solution 1: Make sure the variable is not an undefined object before using it

Using the if statement, you can easily check whether the variable is undefined.

let h1 = 'LearnshareIT';

if (h1) {
  console.log('h1 is not an undefined object');
}

Output:

h1 is not an undefined object

Write code in the block scope of the if statement to avoid the error.

Solution 2: Set the default value before reading the properties

You can set the default value for any variables with the nullish coalescing operator ?? as long as the default value cannot be null or undefined.

const defaultObj = {
  heading: 'LearnshareIT',
};

let h1 = undefined;
let heading = h1 ?? defaultObj.heading;
console.log(heading);

Output:

LearnshareIT

Now, you can read any properties of the heading object and never get the “cannot read properties of undefined in JavaScript” error.

Solution 3: Using optional chaining (?.)

Optional chaining accesses the property or method of an object. If the object is undefined or the property does not exist, it returns undefined instead of throwing an error. Therefore, using optional chaining can help us avoid the error.

let h1 = {
  content: 'LearnshareIT',

  style: {
    color: 'grey',
    font: 'Lato',
  },

};

let h2;
console.log(h1?.style?.color);
console.log(h2?.content);

Output:

grey
undefined

Summary

The “cannot read properties of undefined” error in JavaScript is very common when building web applications. However, by understanding the nature of the problem, we can avoid them easily. Thanks for reading, and I hope this post helps you avoid mistakes.

Lopez

Hi, I’m Cora Lopez. I have a passion for teaching programming languages such as Python, Java, Php, Javascript … I’m creating the free python course online. I hope this helps you in your learning journey.


Name of the university: HCMUE
Major: IT
Programming Languages: HTML/CSS/Javascript, PHP/sql/laravel, Python, Java

As a JavaScript developer, I’m sure you’ve encountered the frustrating runtime TypeError Cannot read properties of undefined.  TypeScript gives you two ways of interpreting null and undefined types, also known as Type Check Modes, and one of them can avoid this easily overlooked TypeError.

Until TypeScript 2.0, there was only one type check mode — regular — and it considersnull and undefined as subtypes of all other types. This means null and undefined values are valid values for all types.

TypeScript 2.0 introduced Strict Type Check Mode (also referred to as strict null checking mode). Strict Type Check differs from Regular Type Check because it considers null and undefined types of their own.

I’ll show you how Regular Type Check handles undefined (the same applies to null) and how Strict Type Check prevents you from introducing unwanted behavior in our code, like that infamous TypeError Cannot read properties of undefined.

When undefined becomes a problem

The function translatePowerLevel below takes a number as argument and returns strings one, two, many or it's over 9000!.

function translatePowerLevel(powerLevel: number): string {

if (powerLevel === 1) {
return 'one';
}
if (powerLevel === 2) {
return 'two';
}
if (powerLevel > 2 && powerLevel <= 9000) {
return 'many';
}
if (powerLevel > 9000) {
return 'it's over 9000!';
}
}

However, this code doesn’t handle 0, a valid input — yes, looking at you, Yamcha.

yamcha

Yamcha’s Power Level

When JavaScript reaches the end of a function that has no explicit return, it returns undefined.

The translatePowerLevel function return value is typed explicitly as string, but it is possibly also returning undefined when the argument powerLevel has the value 0. Why is TypeScript not triggering an error?

In Regular Type Check Mode, TypeScript is aware that a function might return undefined. But at the same time, TypeScript infers the return type to be only of type string because TypeScript is widening the undefined type to string type.

As another example, if you assign null or undefined to variables while in Regular Type Check Mode, TypeScript will infer these variables to be of type any.

const coffee = null; 

const tea = undefined;

Interpreting undefined or null as subtypes of all other types can lead to runtime problems. For example, if you try to get the length of the result of translateNumber(0), which is undefined, JavaScript will throw this TypeError at runtime: Cannot read properties of undefined (reading 'length').

const powerLevel = translatePowerLevel(0); // undefined

console.log(powerLevel.length); // Uncaught TypeError: Cannot read properties of undefined (reading 'length')

Unfortunately, TypeScript’s Regular Type Check Mode is not able to alert you to when you may have made that mistake.

Strict Type Check Mode to the Rescue

Strict Type Check Mode changes how TypeScript interprets undefined and null values. But first, lets enable Strict Type Check Mode.

How to Enable Strict Type Check Mode in TypeScript

In the root of your project, there should be a tsconfig.json file. This is the TypeScript’s configuration file and you can read more about it here.

// tsconfig.json example

{
"compilerOptions": {
"module": "system",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"outFile": "../../built/local/tsc.js",
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}

Inside compilerOptions property, all we need to do is add the property "strictNullChecks": true.

It will look something like this:

// tsconfig.json

{
"compilerOptions": {
"module": "system",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"outFile": "../../built/local/tsc.js",
"sourceMap": true,
"strictNullChecks": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}

Now that we have switched to Strict Type Check Mode, TypeScript throws this error for translatePowerLevel function: Function lacks ending return statement and return type does not include 'undefined'.

That error message is telling you the function is returning undefined implicitly, but its return type does not include undefined in it.

Awesome! TypeScript is now aware the return type does not match all possible return values, and this could lead to problems at runtime! But how can you match the return type to all possible return values?

You can either add a return statement so the function always returns a string (solution #1), or change the return type from string to string | undefined (solution #2).

Match All Possible Return Values: Solution #1

Adding a return statement so it is always explicitly returning a value — in the code below, it is now returning the string zero.

// Solution #1: add a return statement so it always returns a string

function translatePowerLevel(powerLevel: number): string {
if (powerLevel === 1) {
return 'one';
}
if (powerLevel === 2) {
return 'two';
}
if (powerLevel > 2 && powerLevel <= 9000) {
return 'many';
}
if (powerLevel > 9000) {
return 'it's over 9000!';
}
// new return statement
return 'zero';
}

Match All Possible Return Values: Solution #2

Make the undefined return type explicit so wherever translatePowerLevel is used, you have to handle nullish values as well.

// Solution #2: return type as string | undefined

function translatePowerLevel(powerLevel: number): string | undefined {
if (powerLevel === 1) {
return 'one';
}
if (powerLevel === 2) {
return 'two';
}
if (powerLevel > 2 && powerLevel <= 9000) {
return 'many';
}
if (powerLevel > 9000) {
return 'it's over 9000!';
}
}

If you were to compile the following code again using Solution #2, TypeScript would throw the error Object is possibly 'undefined'.

const powerLevel = translatePowerLevel(0); // undefined

console.log(powerLevel.length); // Object is possibly 'undefined'.

When you choose a solution like Solution #2, TypeScript expects you to write code that handles possible nullish values.

There’s no reason not to use Strict Type Check Mode

Now you understand how TypeScript interprets null and undefined types and how you can migrate your project to Strict Mode.

If you are starting a new project, you should definitely enable Strict Type Check Mode from the beginning. And in case you will migrate from Regular to Strict Type Check, our team can help with strategies to do so in a less painful way.

At Bitovi we highly recommend using — or migrating to — Strict Type Check Mode for Angular application development, as it can help you produce better, more reliable code.

Need more help?

Bitovi has expert Angular consultants eager to help support your project. Schedule your free consultation call to get started. 

Если при подписании на сайте ЕИС (ЕРУЗ) 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.ruwww.rts-tender.ru и https://etp.gpb.ru/ . Решение об отключении вы принимаете самостоятельно!

Перезапустите браузер и повторите подписание в ЕИС.

We’ll often run into errors like “Cannot read properties of undefined (reading ‘id’)”. It’s one of the most common errors that developers encounter during web development. Let’s dig in and understand this error, what it means, and how we can debug it.

Breaking down the Message

TypeError: Cannot read properties of undefined (reading 'id')

In older browsers, this might also be shown as:

Cannot read property 'id' of undefined

TypeError is a subset of JavaScript Error that is thrown when code attempts to do something that does not exist on the target object. In this case, our code expects to have an object with a id property, but that object was not present. id is commonly used on HTMLElement, but it could be a custom data object from a remote API as well.

This is a blocking error, and script execution will stop when this error occurs.

Understanding the Root Cause

This error can be thrown for a lot of reasons, as it is not uncommon to look for the id property of an element, or when iterating over a collection of data. For example, let’s say we’re looking for an element in the DOM and reading it’s id.

For example, if we had a function that acts on a string argument, but is called without a string, we would see this error.

var myElement = document.querySelector('#my-element');
console.log(myElement.id);
Logging the id of a found element

But if the query #my-element doesn’t exist in the document, we’ll get null back, which obviously doesn’t have an id property.

Alternatively, you might be making a network request that you expect to return a JSON object with an id property.

fetch('/my/api')
  .then(resp => resp.json())
  .then(json => console.log(json.id));
Logging the id of a json network response

If the API returns an error object, or something else you don’t expect, json may not be defined or not have the expected shape. Or, worse, if the API has a operational failure it can return an HTML error page instead of JSON, leading to errors like SyntaxError: Unexpected Token <.

How to Fix It

So how do we fix this and prevent it from happening again?

1. Understand why your object is undefined

Understand why your object is undefined

First and foremost, you need to understand why this happened before you can fix it. You are probably not doing exactly the same thing we are, so the reason your object is undefined may be somewhat different. Consider:

  • Are you relying on a network response to be a certain shape?
  • Are you processing user-input?
  • Is an external function or library calling into your code?

Or maybe its just a logical bug somewhere in your code.

2. Add Defensive Checking

Add Defensive Checking

Anytime you don’t completely control the input into your code, you need to be defensively checking that arguments have the correct shape. API response change, functions get updated, and users do terrible, terrible things.

For instance, if you have a fetch request that receives a JSON response with a foo string property, you might have a defensive check that looks like this:

fetch("https://example.com/api")
  .then(resp => {
    return resp.json();
  })
  .then(json => {
    if (!json || !json.id) {
      // Record an error, the payload is not the expected shape.
    }
  });
Defensive checking a fetch response

3. Monitor Your Environment

 Monitor Your Environment

You’ll need to make sure that the issue is really fixed and that the problem stops happening. Mistakes happen, APIs change, and users are unpredictable. Just because your application works today, doesn’t mean an error won’t be discovered tomorrow. Tracking when exceptional events happen to your users gives you the context to understand and fix bugs faster. Check out TrackJS Error Monitoring for the fastest and easiest way to get started.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Ошибка cannot open file fsgame ltx check your working folder что делать
  • Ошибка check signal cable
  • Ошибка check rear foglights
  • Ошибка cannot modify header information headers already sent by php
  • Ошибка cannot locate the dvd rom

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

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