Webpack ReferenceError:运行bundle.js时未定义asyncFunc

时间:2019-03-20 14:49:34

标签: webpack babeljs

我是Webpack的新手,我只是想在这里开始一个简单的项目。我拥有运行该应用程序所需的所有依赖关系,但 我在浏览器中运行bundle.js时遇到以下错误:

  

未捕获的ReferenceError:在以下位置未定义asyncFunc   在commitLifeCycles上的App.componentDidMount(index.js?0607:17)   (react-dom.development.js?61bb:17288)在commitAllLifeCycles   (react-dom.development.js?61bb:18690)在   HTMLUnknownElement.callCallback(react-dom.development.js?61bb:149)位于   位于以下位置的Object.invokeGuardedCallbackDev(react-dom.development.js?61bb:199)   at的invokeGuardedCallback(react-dom.development.js?61bb:256)   评估时的commitRoot(react-dom.development.js?61bb:18902)   (react-dom.development.js?61bb:20372)在   Object.unstable_runWithPriority(scheduler.development.js?3069:255)位于   completeRoot(react-dom.development.js?61bb:20371)

这是我的webpack.config.js

const config = {
  entry:['./lib/components/index.js'], 
  output: {
    path: path.resolve(__dirname, 'public'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      { test: /\.js$/, exclude:/node_modules/, use: 'babel-loader' }
    ]
  }
};

module.exports = config;

我的package.json中的依赖项:

"babel": {
    "presets": [
      "react",
      "env",
      "stage-2"
    ]
  },
  "dependencies": {
    "@babel/core": "^7.4.0",
    "babel-cli": "^6.26.0",
    "babel-loader": "^7.1.5",
    "babel-polyfill": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-2": "^6.24.1",
    "ejs": "^2.6.1",
    "express": "^4.16.4",
    "react": "^16.8.4",
    "react-dom": "^16.8.4"
  },

这是我的index.js

import React from 'react';
import ReactDOM from 'react-dom';

import App from './app';

ReactDOM.render(<App />, document.getElementById('content'));

这是index.js

import React from 'react';
import ReactDOM from 'react-dom';


class App extends React.Component{

    asyncFunc = ()=>{

        return 4;
    }

    componentDidMount(){
        asyncFunc();
    }

    render(){
        return <h2>Hello from React</h2>;
    }
}


ReactDOM.render(
    <App/>,
    document.getElementById('root')
);

我该怎么办?

1 个答案:

答案 0 :(得分:1)

您不能直接调用函数,而需要在任何生命周期方法或渲染中将其添加到要调用的函数中

只需this.asyncFunc()即可运行