MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 message lis teners added. Use emitter.setMaxListeners() to increase limit

前端 未结 4 1657
礼貌的吻别
礼貌的吻别 2020-12-20 13:33

I know this might flag as a duplicate solution but solution on stack overflow is not working for me.

Problem:

(node:5716) MaxListenersExceededWarning         


        
4条回答
  •  情书的邮戳
    2020-12-20 14:15

    This is the recommended way to add and remove event listeners within React Components - using LifeCycle methods.

    import { Component } from 'react';
    
    class Example extends Component {
      constructor(props) {
       super(props);
    
       this.state = {
        windowWidth: window.innderWidth,
       };
      }
    
      componentDidMount() {
        window.addEventListener('resize', this.handleResize);
      }
    
      componentWillUnmount() {
        window.removeEventListener('resize', this.handleResize);
      }
    
      handleResize = () => {
        this.setState({ windowWidth: window.innerWidth });
      }
    
      render() {
        return (
          
    Current window width: {this.state.windowWidth}
    ); } }

    It's important to remember that window is within the global execution context. Therefore every time you add an event listener, you're asking the global scope to

    1. instantiate another listener.
    2. track that listener using global memory by reference - in this case resize
    3. continue tracking the listener until told not to.

    If you never tell the global scope to remove those listeners, then the global memory - as allocated by your browser settings - will slowly evaporate and crash your browser & application, or the client's browser if already in production. One must be VERY careful and VERY aware when they manipulate global memory.

    If you want to understand (if you don't already) WHY the lifecycle methods in React Component's work, I would highly recommend you look here at React's Reconciliation lifecycle. One can't accurately call themselves a "React Developer" and not be intimately familiar with Reconciliation.

    Note This Component is using babel to transpile parts of the code: import, and assigned custom method handleResize with only using arrow functions. If you need assistance in setting up the environment, you can refer to this blog post i wrote that should make it understandable.

    Good luck.

提交回复
热议问题