Ошибка загрузки формы typeerror cannot read properties of undefined reading call

I’m pretty new to Next.js and Typescript. I wanna build a project using next.js and typescript and tailwind CSS using this simple create app command:
npx create-next-app -e with-tailwindcss my-project

Everything just went fine until I wanted to use the Image tag using next/image and got an error

Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'call')

Call Stack
options.factory
file:///C:/Users/irwan/Projects/messenger-clone/meta-messenger/.next/static/chunks/webpack.js (710:31)
__webpack_require__
/_next/static/chunks/webpack.js (37:33)
fn
file:///C:/Users/irwan/Projects/messenger-clone/meta-messenger/.next/static/chunks/webpack.js (365:21)
require
node_modulesnextdistclientimage.js (7:15)
./node_modules/next/dist/client/image.js
file:///C:/Users/irwan/Projects/messenger-clone/meta-messenger/.next/static/chunks/app/layout.js (39:1)
options.factory
/_next/static/chunks/webpack.js (710:31)
__webpack_require__
file:///C:/Users/irwan/Projects/messenger-clone/meta-messenger/.next/static/chunks/webpack.js (37:33)
fn
/_next/static/chunks/webpack.js (365:21)
__webpack_require__
node_modulesnextdistclientapp-index.js (26:16)
requireModule
node_modulesnextdistcompiledreact-server-dom-webpackclient.js (142:0)
initializeModuleChunk
node_modulesnextdistcompiledreact-server-dom-webpackclient.js (427:0)
resolveModuleChunk
node_modulesnextdistcompiledreact-server-dom-webpackclient.js (385:0)
eval
node_modulesnextdistcompiledreact-server-dom-webpackclient.js (668:0)

I’m sure the error is not about the URL as I already added the domain to be whitelisted in my next.config.js file.

Here is my package JSON file:

{
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "next": "^13.0.7",
    "react": "18.2.0",
    "react-dom": "18.2.0"
  },
  "devDependencies": {
    "@types/node": "18.11.3",
    "@types/react": "18.0.21",
    "@types/react-dom": "18.0.6",
    "autoprefixer": "^10.4.12",
    "postcss": "^8.4.18",
    "tailwindcss": "^3.2.1",
    "typescript": "^4.8.4"
  }
}

Last I’m using the beta feature(?) appDir on next.js 13. Here is my next.config.js file:

reactStrictMode: true,
  images: {
    domains: ['i.ibb.co']
  },
  experimental: {
    appDir: true
  }

I’m using the image tag on my Header.tsx component. Here is my Header.tsx

import Image from "next/image";
import React from "react";

function Header() {
  const url = "https://i.ibb.co/LhMfkJw/logo-Meta.png";
  return (
    <header>
      <div>
        <div>
          <Image src={url} alt="Logo" width={50} height={10} />
        </div>
      </div>
    </header>
  );
}

export default Header;

And then use that header on my layout.tsx component:

import "../styles/globals.css";
import Header from "./Header";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html>
      <head />
      <body>
        <Header />
        {children}
      </body>
    </html>
  );
}

Thanks for the reply

I’m pretty new to Next.js and Typescript. I wanna build a project using next.js and typescript and tailwind CSS using this simple create app command:
npx create-next-app -e with-tailwindcss my-project

Everything just went fine until I wanted to use the Image tag using next/image and got an error

Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'call')

Call Stack
options.factory
file:///C:/Users/irwan/Projects/messenger-clone/meta-messenger/.next/static/chunks/webpack.js (710:31)
__webpack_require__
/_next/static/chunks/webpack.js (37:33)
fn
file:///C:/Users/irwan/Projects/messenger-clone/meta-messenger/.next/static/chunks/webpack.js (365:21)
require
node_modulesnextdistclientimage.js (7:15)
./node_modules/next/dist/client/image.js
file:///C:/Users/irwan/Projects/messenger-clone/meta-messenger/.next/static/chunks/app/layout.js (39:1)
options.factory
/_next/static/chunks/webpack.js (710:31)
__webpack_require__
file:///C:/Users/irwan/Projects/messenger-clone/meta-messenger/.next/static/chunks/webpack.js (37:33)
fn
/_next/static/chunks/webpack.js (365:21)
__webpack_require__
node_modulesnextdistclientapp-index.js (26:16)
requireModule
node_modulesnextdistcompiledreact-server-dom-webpackclient.js (142:0)
initializeModuleChunk
node_modulesnextdistcompiledreact-server-dom-webpackclient.js (427:0)
resolveModuleChunk
node_modulesnextdistcompiledreact-server-dom-webpackclient.js (385:0)
eval
node_modulesnextdistcompiledreact-server-dom-webpackclient.js (668:0)

I’m sure the error is not about the URL as I already added the domain to be whitelisted in my next.config.js file.

Here is my package JSON file:

{
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "next": "^13.0.7",
    "react": "18.2.0",
    "react-dom": "18.2.0"
  },
  "devDependencies": {
    "@types/node": "18.11.3",
    "@types/react": "18.0.21",
    "@types/react-dom": "18.0.6",
    "autoprefixer": "^10.4.12",
    "postcss": "^8.4.18",
    "tailwindcss": "^3.2.1",
    "typescript": "^4.8.4"
  }
}

Last I’m using the beta feature(?) appDir on next.js 13. Here is my next.config.js file:

reactStrictMode: true,
  images: {
    domains: ['i.ibb.co']
  },
  experimental: {
    appDir: true
  }

I’m using the image tag on my Header.tsx component. Here is my Header.tsx

import Image from "next/image";
import React from "react";

function Header() {
  const url = "https://i.ibb.co/LhMfkJw/logo-Meta.png";
  return (
    <header>
      <div>
        <div>
          <Image src={url} alt="Logo" width={50} height={10} />
        </div>
      </div>
    </header>
  );
}

export default Header;

And then use that header on my layout.tsx component:

import "../styles/globals.css";
import Header from "./Header";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html>
      <head />
      <body>
        <Header />
        {children}
      </body>
    </html>
  );
}

Thanks for the reply

Допустим, вы делаете страницу с формой и полем ввода:

<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="...">

Второй вариант — поместить вызов скрипта сразу после формы, тогда к моменту вызова всё окажется на своих местах и ошибки не будет. Или вообще в конце всего документа.

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!

  • Ошибка загрузки фонта код ошибки 28 цивилизация 3 windows 10
  • Ошибка заднего левого датчика абс
  • Ошибка загрузки файлов обновлений kes 11
  • Ошибка задачи защита отключена kaspersky linux
  • Ошибка загрузки файлов мобайл легенд