Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

106
Vistas
Getting a warning called Can't call setState on a component that is not yet mounted

This is my code

import React, { Component } from 'react';

class Rando extends Component {
    constructor(props) {
        super(props); // want to use props insode brackets if we want to use props inside the constructor
        this.state = { num: 0, color: 'purple' };
        this.makeTimer();
    }

    makeTimer() {
        setInterval(() => {
            let rand = Math.floor(Math.random() * this.props.maxNum);

            this.setState({ num: rand });
        }, 10);
    }
    render() {
        console.log('changing');
        return (
            <div className=''>
                <h1>{this.state.num}</h1>
            </div>
        );
    }
}

export default Rando;

I'm getting a warning that looks like this

index.js:1 Warning: Can't call setState on a component that is not yet mounted. 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 Rando component.

I'm a beginner, I have no idea what's causing this. please help me. Thanks in advance

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Your timer function gets executed even before the component gets mounted. Try putting the code inside componentDidMount hook. Also don't forget to clear the interval id inside componentWillUnmount.

Sandbox link for your reference: https://codesandbox.io/s/react-basic-class-component-forked-sybv0?file=/src/index.js

Modified Snippet

import React, { Component } from 'react';

class Rando extends Component {
    constructor(props) {
        super(props); 
        this.state = { num: 0, color: 'purple' };
        this.timer = null;
    }

     componentDidMount() {
        this.makeTimer();
     }
   
     componentWillUnmount() {
        clearInterval(this.timer);
     }

    makeTimer = () => {
        this.timer = setInterval(() => {
            let rand = Math.floor(Math.random() * this.props.maxNum);
            this.setState({ num: rand });
        }, 10);
    }

    render() {
        return (
            <div>
                <h1>{this.state.num}</h1>
            </div>
        );
    }
}

export default Rando;
about 4 years ago · Juan Pablo Isaza Denunciar

0

You should call this.makeTimer(); on componentDidMount() instead of constructor

componentDidMount(){
  this.makeTimer();
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Try this code

import React, { Component } from 'react';

class Rando extends Component {
    constructor(props) {
        super(props); // want to use props insode brackets if we want to use props inside the constructor
        this.state = { num: 0, color: 'purple' };
        this.makeTimer((data) => {
          this.setState(data);
        });
    }

    makeTimer(cb) {
        setInterval(() => {
            let rand = Math.floor(Math.random() * this.props.maxNum);

            
            cb({ num: rand })
        }, 10);
    }
    render() {
        console.log('changing');
        return (
            <div className=''>
                <h1>{this.state.num}</h1>
            </div>
        );
    }
}

export default Rando;

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda