2017-07-03 36 views
1

我一直在追逐這個bug。我有一個簡單的React入口點和一個簡單的組件狀態更改示例組件。如果我將組件插入入口點,如下所示:獲取React錯誤:「setState(...):只能使用子組件更新已安裝或掛載組件」

import React from 'react'; 
import { render } from 'react-dom'; 

export default class Template extends React.Component { 
    constructor(props) { 
    super(props); 

    this.toggleNavbar = this.toggleNavbar.bind(this); 
    this.state = { 
     collapsed: true, 
    }; 
    } 

    toggleNavbar() { 
    this.setState({ 
     collapsed: !this.state.collapsed, 
    }); 
    } 
    render() { 
    return (
     <div> 
     <p>Collapsed: { this.state.collapsed ? 'true' : 'false' }</p> 
     <button onClick={this.toggleNavbar}>Toggle</button> 
     </div> 
    ); 
    } 
} 

render(
    <Template />, 
    document.querySelector('#react-app'), 
); 

它按預期工作。您單擊切換按鈕,文本在「真」和「假」之間來回切換。然而,分鐘,我打破它分成兩個獨立的文件,給我這個爲切入點:

import React from 'react'; 
import { render } from 'react-dom'; 

import Template from './components/Template'; 

render(
    <Template />, 
    document.querySelector('#react-app'), 
); 

這對於Template.jsx

import React from 'react'; 

export default class Template extends React.Component { 
    constructor(props) { 
    super(props); 

    this.toggleNavbar = this.toggleNavbar.bind(this); 
    this.state = { 
     collapsed: true, 
    }; 
    } 

    toggleNavbar() { 
    this.setState({ 
     collapsed: !this.state.collapsed, 
    }); 
    } 
    render() { 
    return (
     <div> 
     <p>Collapsed: { this.state.collapsed ? 'true' : 'false' }</p> 
     <button onClick={this.toggleNavbar}>Toggle</button> 
     </div> 
    ); 
    } 
} 

任何時候,我按一下按鈕我得到在控制檯中出現以下錯誤:

build.js:23484警告:setState(...):只能更新已安裝或掛載的組件。這通常意味着您在卸載的組件上調用了setState()。這是一個沒有操作。請檢查模板組件的代碼。

...我已經檢查了所有其他堆棧溢出的錯誤(也搜索了一噸左右)的答案,並沒有一個似乎適用於這裏。任何人有任何想法我做錯了什麼?

側面說明:我已經嘗試添加:

componentWillUnmount() { 
    this.isUnmounted = true; 
} 

!this.isUnmounted檢查setState()之前,我仍然得到錯誤。

謝謝!

+1

我試過剝下一個'創建 - 反應 - 應用程序'到裸露的骨頭,並在創建的應用程序中運行您的代碼,它只是適用於我。這導致我認爲它更可能是建築/捆綁產生的問題。我的github回購你的問題是https://github.com/finbarrobrien/react-setstate –

+0

試試這個'onClick = {()=> {this.toggleNavbar()}}'。還要將jsx文件擴展名添加到您的導入語句'import template from'./components/Template.jsx';' – Fawaz

+0

@ FinbarrO'B - 謝謝。是的,這是一個捆綁問題。我從零開始創建一個全新的應用程序(就像您所做的那樣)並設置了所有內容後找到了問題。原來我的.babelrc中有一個錯誤的行:''plugins「:[」react-hot-loader/babel「]'我認爲發生了什麼事情,這與我的webpack熱重裝有某些衝突。無論如何,刪除它解決了這個問題。 –

回答

2

我發現了問題:我.babelrc包含這一行:

"plugins": ["react-hot-loader/babel"] 

,這是我的WebPack熱重裝安裝的其他部分相沖突。去掉那條線就行了。我認爲發生的事情是該組件正在渲染,但不知怎麼的反應是對什麼是/未安裝(可能是非常快速進行安裝,卸載,然後重新安裝,所以綁定的toggleClick功能試圖在舊版本的組件上設置狀態?不確定)。

無論如何,故事的寓意是:React代碼很好。這是我的配置問題。

相關問題