![](/img/trans.png)
[英]React Warning: Can't call setState (or forceUpdate) on an unmounted component
[英]Warning: Can't call setState (or forceUpdate) on an unmounted component
我每次登錄時都會收到此警告,
警告:無法在卸載的組件上調用setState(或forceUpdate)。 這是一個無操作,但它表示應用程序中存在內存泄漏。 要修復,請取消componentWillUnmount方法中的所有訂閱和異步任務。
這是我的代碼:
authpage.js
handleLoginSubmit = (e) => {
e.preventDefault()
let { email,password } = this.state
const data = {
email : email,
password : password
}
fetch('http://localhost:3001/auth/login',{
method : 'post',
body : JSON.stringify(data),
headers : {
"Content-Type":"application/json"
}
}).then(res => res.json())
.then(data => {
if(data.success){
sessionStorage.setItem('userid',data.user.id)
sessionStorage.setItem('email',data.user.email)
}
this.setState({loginData : data,
userData : data,
email:"",
password:""})
if(data.token) {
Auth.authenticateUser(data.token)
this.props.history.push('/dashboard')
}
this.handleLoginMessage()
this.isUserAuthenticated()
})
}
export default withRouter(AuthPage)
使用withRouter
所以我可以訪問我用來導航this.props.history.push('/dashboard')
道具,如果我沒有使用withRouter我無法訪問this.props
index.js
const PrivateRoute = ({ component : Component, ...rest }) => {
return (
<Route {...rest} render = { props => (
Auth.isUserAuthenticated() ? (
<Component {...props} {...rest} />
) : (
<Redirect to = {{
pathname: '/',
state: { from: props.location }
}}/>
)
)}/>
)
}
const PropsRoute = ({ component : Component, ...rest }) => (
<Route {...rest} render = { props => (
<Component {...props} {...rest} />
)}/>
)
const Root = () => (
<BrowserRouter>
<Switch>
<PropsRoute exact path = "/" component = { AuthPage } />
<PrivateRoute path = "/dashboard" component = { DashboardPage } />
<Route path = "/logout" component = { LogoutFunction } />
<Route component = { () => <h1> Page Not Found </h1> } />
</Switch>
</BrowserRouter>
)
我認為問題在於我的withRouter,如何在不使用withRouter的情況下訪問this.props?
這是異步的
this.setState({
loginData : data,
userData : data,
email:"",
password:""
})
make error您可以使用this._mount檢查組件是已掛載還是已卸載
componentDidMount () {
this._mounted = true
}
componentWillUnmount () {
this._mounted = false
}
...
if(this._mounted) {
this.setState({
loginData : data,
userData : data,
email:"",
password:""
})
...
您可以使用_isMount
重載setState
函數:
componentWillUnmount() {
this._isMount = false;
}
componentDidMount() {
this._isMount = true;
}
setState(params) {
if (this._isMount) {
super.setState(params);
}
}
我在使用this.setState({ any })
遇到了一些問題。
每次構建組件時,它都會調用一個使用Axios的函數,並且響應產生了一個this.setState({ any })
。
我的問題解決了如下:
在componentDidMount()
函數中,我調用另一個名為initialize()
函數,我將其保留為異步 ,通過它我可以調用執行fetch和this.setState({ any })
函數。
componentDidMount() {
this.initialize();
}
myFunction = async () => {
const { data: any } = await AnyApi.fetchAny();
this.setState({ any });
}
initialize = async () => {
await this.myFunction();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.