Can't call setState on a component that is not yet mountedWhat is “Mounting” in React js?Can't call setState on a Component that is not yet mounted - tsxCannot control state properlyWhat is the difference between call and apply?How do I return the response from an asynchronous call?Can you force a React component to rerender without calling setState?Invariant Violation: Objects are not valid as a React childReact - setState(…) Can only update a mounted or mounting componentreact-data-components renders component (a button) but can't access state or function defined outside the render methodStore change doesn't re-render computed function in componentReact app. Can't call setState on a component that is not yet mountedsetState() bug when triggered from child component with callbackReact components not mounting

How can I calculate the cost of Skyss bus tickets

Create a dropshadow only layer

Adding gears to my grandson's 12" bike

Can't understand how static works exactly

What's the meaning of reading light at X degree angle

Host telling me to cancel my booking in exchange for a discount?

An Italian table, is it in fact Arabic?

High income and difficulty during interviews

What is an expert set in the fonts field?

Why is the UH-60 tail rotor canted?

How often should alkaline batteries be checked when they are in a device?

What is "ass door"?

Finding number of days per ID in table using ArcPy?

Was US film used in Luna 3?

Storyboard broken after updating Xcode to version 10.3 (10G8) & app no longer is running

Are rockets faster than airplanes?

Are there any documented cases of extinction of a species of fungus?

Found more old paper shares from broken up companies

I have a domain, static IP address and many devices I'd like to access outside my house. How do I route them?

What is the minimum altitude over Egmond aan Zee when landing at Schiphol?

How can I show that the speed of light in vacuum is the same in all reference frames?

Tire pressure with load and heat

Is there a way to shorten this while condition?

How did pilots avoid thunderstorms and related weather before “reliable” airborne weather radar was introduced on airliners?



Can't call setState on a component that is not yet mounted


What is “Mounting” in React js?Can't call setState on a Component that is not yet mounted - tsxCannot control state properlyWhat is the difference between call and apply?How do I return the response from an asynchronous call?Can you force a React component to rerender without calling setState?Invariant Violation: Objects are not valid as a React childReact - setState(…) Can only update a mounted or mounting componentreact-data-components renders component (a button) but can't access state or function defined outside the render methodStore change doesn't re-render computed function in componentReact app. Can't call setState on a component that is not yet mountedsetState() bug when triggered from child component with callbackReact components not mounting






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








14















this is the first time I face this warning message.




Can't call setState on a component that is not yet mounted.




Follows:




This is a no-op, but it might indicate a bug in your application. Instead, assign to this.state directly or define a state = ; class property with the desired state in the MyComponent component.




The "not yet mounted" part actually makes little to no sense as the only way to trigger the issue is to call a function by clicking a button from a component that needs to be mounted in order to see the button. The component is not unmounted at any given time neither.



This dummy component reproduces the error in my app:



import PropTypes from 'prop-types'
import React from 'react'

export default class MyComponent extends React.Component
constructor (props)
super(props)
this.state =
initial: 'state'

this.clickMe = this.clickMe.bind(this)


clickMe ()
this.setState(
some: 'new state'
)


render ()
return (
<div>
<button onClick=this.clickMe>click</button>
</div>
)




I am using:



"react": "16.3.2",
"react-dom": "16.3.2",
"mobx": "4.2.0",
"mobx-react": "5.1.2",


Did I miss something in the latest React/mobx version? (note the component does not use any mobx related stuff but its parent is a mobx-react observer)



Edit:



There must be something related to the component instance, further investigation has shown that in some cases, creating an handler inside the render function will make this warning disappear, but not in all cases.



class MyComponent extends React.component 
constructor (props)
// ...
this.clickMeBound = this.clickMe.bind(this)


clickMe ()
...


render ()
// works
<button onClick=() => this.clickMe()>click arrow in render</button>

// warning: Can't call setState on a component that is not yet mounted.
<button onClick=this.clickMeBound>click bound</button>




Edit 2:



I have removed 'react-hot-loader/patch' from my entries in my Webpack config and some weird issues like this one have disappeared. I'm not putting this as an answer because the error message itself is still weird and this causes a warning in the console. Everything works fine though.










share|improve this question
























  • Have you tried to add a componentWillUnmount function and make 100% sure your component isn't getting unmounted? If it's getting unmounted, then the problem is not in your component.

    – Ryan Wheale
    May 3 '18 at 19:29











  • Yes, that's what I meant by "The component is not unmounted at any given time neither."

    – Kev
    May 3 '18 at 19:34











  • Your code seems perfectly valid maybe have a double parenthesis after bind? bind()()?

    – Joel Harkes
    May 3 '18 at 20:26






  • 1





    I don't have time to prove it right now, but it could be related to the use of react hot loader. I have removed 'react-hot-loader/patch' from my entries in my webpack config and some weird issues disappeared.

    – Kev
    Jun 19 '18 at 22:22


















14















this is the first time I face this warning message.




Can't call setState on a component that is not yet mounted.




Follows:




This is a no-op, but it might indicate a bug in your application. Instead, assign to this.state directly or define a state = ; class property with the desired state in the MyComponent component.




The "not yet mounted" part actually makes little to no sense as the only way to trigger the issue is to call a function by clicking a button from a component that needs to be mounted in order to see the button. The component is not unmounted at any given time neither.



This dummy component reproduces the error in my app:



import PropTypes from 'prop-types'
import React from 'react'

export default class MyComponent extends React.Component
constructor (props)
super(props)
this.state =
initial: 'state'

this.clickMe = this.clickMe.bind(this)


clickMe ()
this.setState(
some: 'new state'
)


render ()
return (
<div>
<button onClick=this.clickMe>click</button>
</div>
)




I am using:



"react": "16.3.2",
"react-dom": "16.3.2",
"mobx": "4.2.0",
"mobx-react": "5.1.2",


Did I miss something in the latest React/mobx version? (note the component does not use any mobx related stuff but its parent is a mobx-react observer)



Edit:



There must be something related to the component instance, further investigation has shown that in some cases, creating an handler inside the render function will make this warning disappear, but not in all cases.



class MyComponent extends React.component 
constructor (props)
// ...
this.clickMeBound = this.clickMe.bind(this)


clickMe ()
...


render ()
// works
<button onClick=() => this.clickMe()>click arrow in render</button>

// warning: Can't call setState on a component that is not yet mounted.
<button onClick=this.clickMeBound>click bound</button>




Edit 2:



I have removed 'react-hot-loader/patch' from my entries in my Webpack config and some weird issues like this one have disappeared. I'm not putting this as an answer because the error message itself is still weird and this causes a warning in the console. Everything works fine though.










share|improve this question
























  • Have you tried to add a componentWillUnmount function and make 100% sure your component isn't getting unmounted? If it's getting unmounted, then the problem is not in your component.

    – Ryan Wheale
    May 3 '18 at 19:29











  • Yes, that's what I meant by "The component is not unmounted at any given time neither."

    – Kev
    May 3 '18 at 19:34











  • Your code seems perfectly valid maybe have a double parenthesis after bind? bind()()?

    – Joel Harkes
    May 3 '18 at 20:26






  • 1





    I don't have time to prove it right now, but it could be related to the use of react hot loader. I have removed 'react-hot-loader/patch' from my entries in my webpack config and some weird issues disappeared.

    – Kev
    Jun 19 '18 at 22:22














14












14








14


1






this is the first time I face this warning message.




Can't call setState on a component that is not yet mounted.




Follows:




This is a no-op, but it might indicate a bug in your application. Instead, assign to this.state directly or define a state = ; class property with the desired state in the MyComponent component.




The "not yet mounted" part actually makes little to no sense as the only way to trigger the issue is to call a function by clicking a button from a component that needs to be mounted in order to see the button. The component is not unmounted at any given time neither.



This dummy component reproduces the error in my app:



import PropTypes from 'prop-types'
import React from 'react'

export default class MyComponent extends React.Component
constructor (props)
super(props)
this.state =
initial: 'state'

this.clickMe = this.clickMe.bind(this)


clickMe ()
this.setState(
some: 'new state'
)


render ()
return (
<div>
<button onClick=this.clickMe>click</button>
</div>
)




I am using:



"react": "16.3.2",
"react-dom": "16.3.2",
"mobx": "4.2.0",
"mobx-react": "5.1.2",


Did I miss something in the latest React/mobx version? (note the component does not use any mobx related stuff but its parent is a mobx-react observer)



Edit:



There must be something related to the component instance, further investigation has shown that in some cases, creating an handler inside the render function will make this warning disappear, but not in all cases.



class MyComponent extends React.component 
constructor (props)
// ...
this.clickMeBound = this.clickMe.bind(this)


clickMe ()
...


render ()
// works
<button onClick=() => this.clickMe()>click arrow in render</button>

// warning: Can't call setState on a component that is not yet mounted.
<button onClick=this.clickMeBound>click bound</button>




Edit 2:



I have removed 'react-hot-loader/patch' from my entries in my Webpack config and some weird issues like this one have disappeared. I'm not putting this as an answer because the error message itself is still weird and this causes a warning in the console. Everything works fine though.










share|improve this question
















this is the first time I face this warning message.




Can't call setState on a component that is not yet mounted.




Follows:




This is a no-op, but it might indicate a bug in your application. Instead, assign to this.state directly or define a state = ; class property with the desired state in the MyComponent component.




The "not yet mounted" part actually makes little to no sense as the only way to trigger the issue is to call a function by clicking a button from a component that needs to be mounted in order to see the button. The component is not unmounted at any given time neither.



This dummy component reproduces the error in my app:



import PropTypes from 'prop-types'
import React from 'react'

export default class MyComponent extends React.Component
constructor (props)
super(props)
this.state =
initial: 'state'

this.clickMe = this.clickMe.bind(this)


clickMe ()
this.setState(
some: 'new state'
)


render ()
return (
<div>
<button onClick=this.clickMe>click</button>
</div>
)




I am using:



"react": "16.3.2",
"react-dom": "16.3.2",
"mobx": "4.2.0",
"mobx-react": "5.1.2",


Did I miss something in the latest React/mobx version? (note the component does not use any mobx related stuff but its parent is a mobx-react observer)



Edit:



There must be something related to the component instance, further investigation has shown that in some cases, creating an handler inside the render function will make this warning disappear, but not in all cases.



class MyComponent extends React.component 
constructor (props)
// ...
this.clickMeBound = this.clickMe.bind(this)


clickMe ()
...


render ()
// works
<button onClick=() => this.clickMe()>click arrow in render</button>

// warning: Can't call setState on a component that is not yet mounted.
<button onClick=this.clickMeBound>click bound</button>




Edit 2:



I have removed 'react-hot-loader/patch' from my entries in my Webpack config and some weird issues like this one have disappeared. I'm not putting this as an answer because the error message itself is still weird and this causes a warning in the console. Everything works fine though.







javascript reactjs mobx mobx-react






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 28 '18 at 23:09







Kev

















asked May 3 '18 at 19:25









KevKev

2,0783 gold badges19 silver badges29 bronze badges




2,0783 gold badges19 silver badges29 bronze badges












  • Have you tried to add a componentWillUnmount function and make 100% sure your component isn't getting unmounted? If it's getting unmounted, then the problem is not in your component.

    – Ryan Wheale
    May 3 '18 at 19:29











  • Yes, that's what I meant by "The component is not unmounted at any given time neither."

    – Kev
    May 3 '18 at 19:34











  • Your code seems perfectly valid maybe have a double parenthesis after bind? bind()()?

    – Joel Harkes
    May 3 '18 at 20:26






  • 1





    I don't have time to prove it right now, but it could be related to the use of react hot loader. I have removed 'react-hot-loader/patch' from my entries in my webpack config and some weird issues disappeared.

    – Kev
    Jun 19 '18 at 22:22


















  • Have you tried to add a componentWillUnmount function and make 100% sure your component isn't getting unmounted? If it's getting unmounted, then the problem is not in your component.

    – Ryan Wheale
    May 3 '18 at 19:29











  • Yes, that's what I meant by "The component is not unmounted at any given time neither."

    – Kev
    May 3 '18 at 19:34











  • Your code seems perfectly valid maybe have a double parenthesis after bind? bind()()?

    – Joel Harkes
    May 3 '18 at 20:26






  • 1





    I don't have time to prove it right now, but it could be related to the use of react hot loader. I have removed 'react-hot-loader/patch' from my entries in my webpack config and some weird issues disappeared.

    – Kev
    Jun 19 '18 at 22:22

















Have you tried to add a componentWillUnmount function and make 100% sure your component isn't getting unmounted? If it's getting unmounted, then the problem is not in your component.

– Ryan Wheale
May 3 '18 at 19:29





Have you tried to add a componentWillUnmount function and make 100% sure your component isn't getting unmounted? If it's getting unmounted, then the problem is not in your component.

– Ryan Wheale
May 3 '18 at 19:29













Yes, that's what I meant by "The component is not unmounted at any given time neither."

– Kev
May 3 '18 at 19:34





Yes, that's what I meant by "The component is not unmounted at any given time neither."

– Kev
May 3 '18 at 19:34













Your code seems perfectly valid maybe have a double parenthesis after bind? bind()()?

– Joel Harkes
May 3 '18 at 20:26





Your code seems perfectly valid maybe have a double parenthesis after bind? bind()()?

– Joel Harkes
May 3 '18 at 20:26




1




1





I don't have time to prove it right now, but it could be related to the use of react hot loader. I have removed 'react-hot-loader/patch' from my entries in my webpack config and some weird issues disappeared.

– Kev
Jun 19 '18 at 22:22






I don't have time to prove it right now, but it could be related to the use of react hot loader. I have removed 'react-hot-loader/patch' from my entries in my webpack config and some weird issues disappeared.

– Kev
Jun 19 '18 at 22:22













3 Answers
3






active

oldest

votes


















1














Just add this line of code to the code



export default class MyComponent extends React.Component 
constructor (props)
super(props)
this.state =
initial: 'state',
some: '' // <------- this line

this.clickMe = this.clickMe.bind(this)


clickMe ()
this.setState(
some: 'new state'
)


render ()
return (
<div>
<button onClick=this.clickMe>click</button>
</div>
);







share|improve this answer






























    1














    As @Amida mentioned, hot-loader seems to be the issue. Whoever is using



    app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions

    HotModuleReplacement = true,
    ReactHotModuleReplacement = true
    );


    in Startup.cs, remove it and the issue will disappear. I don't know why, but this is my current workaround.



    EDIT:



    Update of "react-hot-loader" and "webpack-hot-middleware" to latest versions fixed the issue






    share|improve this answer
































      0














      If this error is happening in one of your tests, you might need to render the component to an element before accessing it (i.e. simply doing let app = new App; is not enough). Rendering will effectively mount the component and its children, as explained in this other answer and then you will be able to use the result object to perform operations without triggering the setState error. A simple App.test.js example:



      import App from './App';

      it('renders without crashing', () =>
      const div = document.createElement('div');
      ReactDOM.render(<App />, div); // <-- App component mounted here
      // without JSX: ReactDOM.render(React.createElement(App), div)
      ReactDOM.unmountComponentAtNode(div);
      );

      test('array length decreased after removal', () =>
      const div = document.createElement('div');
      let app = ReactDOM.render(<App />, div); // <-- App component mounted here
      const origArrLen = app.state.arr.length;

      app.removeAtIndex(0);
      expect(app.state.arr.length).toEqual(origArrLen - 1);
      ReactDOM.unmountComponentAtNode(div);
      );


      Where the App component could have:



      class App extends Component 
      state =
      arr: [1,2,3]
      ;

      removeAtIndex = index =>
      const arr = this.state;
      this.setState( arr: arr.filter((el, i) => i !== index) );
      ;
      // render() return ( ... )






      share|improve this answer

























        Your Answer






        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f50162522%2fcant-call-setstate-on-a-component-that-is-not-yet-mounted%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1














        Just add this line of code to the code



        export default class MyComponent extends React.Component 
        constructor (props)
        super(props)
        this.state =
        initial: 'state',
        some: '' // <------- this line

        this.clickMe = this.clickMe.bind(this)


        clickMe ()
        this.setState(
        some: 'new state'
        )


        render ()
        return (
        <div>
        <button onClick=this.clickMe>click</button>
        </div>
        );







        share|improve this answer



























          1














          Just add this line of code to the code



          export default class MyComponent extends React.Component 
          constructor (props)
          super(props)
          this.state =
          initial: 'state',
          some: '' // <------- this line

          this.clickMe = this.clickMe.bind(this)


          clickMe ()
          this.setState(
          some: 'new state'
          )


          render ()
          return (
          <div>
          <button onClick=this.clickMe>click</button>
          </div>
          );







          share|improve this answer

























            1












            1








            1







            Just add this line of code to the code



            export default class MyComponent extends React.Component 
            constructor (props)
            super(props)
            this.state =
            initial: 'state',
            some: '' // <------- this line

            this.clickMe = this.clickMe.bind(this)


            clickMe ()
            this.setState(
            some: 'new state'
            )


            render ()
            return (
            <div>
            <button onClick=this.clickMe>click</button>
            </div>
            );







            share|improve this answer













            Just add this line of code to the code



            export default class MyComponent extends React.Component 
            constructor (props)
            super(props)
            this.state =
            initial: 'state',
            some: '' // <------- this line

            this.clickMe = this.clickMe.bind(this)


            clickMe ()
            this.setState(
            some: 'new state'
            )


            render ()
            return (
            <div>
            <button onClick=this.clickMe>click</button>
            </div>
            );








            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered May 27 '18 at 10:48









            Mahdi BashirpourMahdi Bashirpour

            2,8752 gold badges20 silver badges43 bronze badges




            2,8752 gold badges20 silver badges43 bronze badges























                1














                As @Amida mentioned, hot-loader seems to be the issue. Whoever is using



                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions

                HotModuleReplacement = true,
                ReactHotModuleReplacement = true
                );


                in Startup.cs, remove it and the issue will disappear. I don't know why, but this is my current workaround.



                EDIT:



                Update of "react-hot-loader" and "webpack-hot-middleware" to latest versions fixed the issue






                share|improve this answer





























                  1














                  As @Amida mentioned, hot-loader seems to be the issue. Whoever is using



                  app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions

                  HotModuleReplacement = true,
                  ReactHotModuleReplacement = true
                  );


                  in Startup.cs, remove it and the issue will disappear. I don't know why, but this is my current workaround.



                  EDIT:



                  Update of "react-hot-loader" and "webpack-hot-middleware" to latest versions fixed the issue






                  share|improve this answer



























                    1












                    1








                    1







                    As @Amida mentioned, hot-loader seems to be the issue. Whoever is using



                    app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions

                    HotModuleReplacement = true,
                    ReactHotModuleReplacement = true
                    );


                    in Startup.cs, remove it and the issue will disappear. I don't know why, but this is my current workaround.



                    EDIT:



                    Update of "react-hot-loader" and "webpack-hot-middleware" to latest versions fixed the issue






                    share|improve this answer















                    As @Amida mentioned, hot-loader seems to be the issue. Whoever is using



                    app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions

                    HotModuleReplacement = true,
                    ReactHotModuleReplacement = true
                    );


                    in Startup.cs, remove it and the issue will disappear. I don't know why, but this is my current workaround.



                    EDIT:



                    Update of "react-hot-loader" and "webpack-hot-middleware" to latest versions fixed the issue







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jan 15 at 14:52

























                    answered Jan 15 at 14:12









                    Antoan ElenkovAntoan Elenkov

                    791 gold badge1 silver badge8 bronze badges




                    791 gold badge1 silver badge8 bronze badges





















                        0














                        If this error is happening in one of your tests, you might need to render the component to an element before accessing it (i.e. simply doing let app = new App; is not enough). Rendering will effectively mount the component and its children, as explained in this other answer and then you will be able to use the result object to perform operations without triggering the setState error. A simple App.test.js example:



                        import App from './App';

                        it('renders without crashing', () =>
                        const div = document.createElement('div');
                        ReactDOM.render(<App />, div); // <-- App component mounted here
                        // without JSX: ReactDOM.render(React.createElement(App), div)
                        ReactDOM.unmountComponentAtNode(div);
                        );

                        test('array length decreased after removal', () =>
                        const div = document.createElement('div');
                        let app = ReactDOM.render(<App />, div); // <-- App component mounted here
                        const origArrLen = app.state.arr.length;

                        app.removeAtIndex(0);
                        expect(app.state.arr.length).toEqual(origArrLen - 1);
                        ReactDOM.unmountComponentAtNode(div);
                        );


                        Where the App component could have:



                        class App extends Component 
                        state =
                        arr: [1,2,3]
                        ;

                        removeAtIndex = index =>
                        const arr = this.state;
                        this.setState( arr: arr.filter((el, i) => i !== index) );
                        ;
                        // render() return ( ... )






                        share|improve this answer



























                          0














                          If this error is happening in one of your tests, you might need to render the component to an element before accessing it (i.e. simply doing let app = new App; is not enough). Rendering will effectively mount the component and its children, as explained in this other answer and then you will be able to use the result object to perform operations without triggering the setState error. A simple App.test.js example:



                          import App from './App';

                          it('renders without crashing', () =>
                          const div = document.createElement('div');
                          ReactDOM.render(<App />, div); // <-- App component mounted here
                          // without JSX: ReactDOM.render(React.createElement(App), div)
                          ReactDOM.unmountComponentAtNode(div);
                          );

                          test('array length decreased after removal', () =>
                          const div = document.createElement('div');
                          let app = ReactDOM.render(<App />, div); // <-- App component mounted here
                          const origArrLen = app.state.arr.length;

                          app.removeAtIndex(0);
                          expect(app.state.arr.length).toEqual(origArrLen - 1);
                          ReactDOM.unmountComponentAtNode(div);
                          );


                          Where the App component could have:



                          class App extends Component 
                          state =
                          arr: [1,2,3]
                          ;

                          removeAtIndex = index =>
                          const arr = this.state;
                          this.setState( arr: arr.filter((el, i) => i !== index) );
                          ;
                          // render() return ( ... )






                          share|improve this answer

























                            0












                            0








                            0







                            If this error is happening in one of your tests, you might need to render the component to an element before accessing it (i.e. simply doing let app = new App; is not enough). Rendering will effectively mount the component and its children, as explained in this other answer and then you will be able to use the result object to perform operations without triggering the setState error. A simple App.test.js example:



                            import App from './App';

                            it('renders without crashing', () =>
                            const div = document.createElement('div');
                            ReactDOM.render(<App />, div); // <-- App component mounted here
                            // without JSX: ReactDOM.render(React.createElement(App), div)
                            ReactDOM.unmountComponentAtNode(div);
                            );

                            test('array length decreased after removal', () =>
                            const div = document.createElement('div');
                            let app = ReactDOM.render(<App />, div); // <-- App component mounted here
                            const origArrLen = app.state.arr.length;

                            app.removeAtIndex(0);
                            expect(app.state.arr.length).toEqual(origArrLen - 1);
                            ReactDOM.unmountComponentAtNode(div);
                            );


                            Where the App component could have:



                            class App extends Component 
                            state =
                            arr: [1,2,3]
                            ;

                            removeAtIndex = index =>
                            const arr = this.state;
                            this.setState( arr: arr.filter((el, i) => i !== index) );
                            ;
                            // render() return ( ... )






                            share|improve this answer













                            If this error is happening in one of your tests, you might need to render the component to an element before accessing it (i.e. simply doing let app = new App; is not enough). Rendering will effectively mount the component and its children, as explained in this other answer and then you will be able to use the result object to perform operations without triggering the setState error. A simple App.test.js example:



                            import App from './App';

                            it('renders without crashing', () =>
                            const div = document.createElement('div');
                            ReactDOM.render(<App />, div); // <-- App component mounted here
                            // without JSX: ReactDOM.render(React.createElement(App), div)
                            ReactDOM.unmountComponentAtNode(div);
                            );

                            test('array length decreased after removal', () =>
                            const div = document.createElement('div');
                            let app = ReactDOM.render(<App />, div); // <-- App component mounted here
                            const origArrLen = app.state.arr.length;

                            app.removeAtIndex(0);
                            expect(app.state.arr.length).toEqual(origArrLen - 1);
                            ReactDOM.unmountComponentAtNode(div);
                            );


                            Where the App component could have:



                            class App extends Component 
                            state =
                            arr: [1,2,3]
                            ;

                            removeAtIndex = index =>
                            const arr = this.state;
                            this.setState( arr: arr.filter((el, i) => i !== index) );
                            ;
                            // render() return ( ... )







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 26 at 14:10









                            CPHPythonCPHPython

                            2,6551 gold badge14 silver badges33 bronze badges




                            2,6551 gold badge14 silver badges33 bronze badges



























                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f50162522%2fcant-call-setstate-on-a-component-that-is-not-yet-mounted%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                                155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해