运行ReactJs代码时出现此错误:
index.js:1375警告:无法在已卸载的组件上执行React状态更新。这是空操作,但它表明应用程序中发生内存泄漏。要修复此问题,请取消componentWillUnmount方法中的所有订阅和异步任务。
我尝试了以下代码,但是仍然遇到相同的错误。我在componentDidMount上看到了API调用在stackoverflow上的代码,但是我的代码来自Redux。如何在componentWillUnmount中取消订阅或取消订阅和异步任务?
整夜都在挣扎。
这是我的减速器:
const initState = {
error_message: null,
patient : null,
isLoading: true,
patients: [],
}
const patientReducer = (state = initState, action) => {
switch (action.type){
case ALL_PATIENT_ERROR:
case SHOW_PATIENT_ERROR:
console.log(action.payload)
return {
...state,
error_message: action.payload
}
case SHOW_PATIENT_SUCCESS:
return {
...state,
patient : action.payload.patient,
isLoading: false
}
case ALL_PATIENT_SUCCESS:
return {
...state,
patients : action.payload,
isLoading: false
}
default:
return state
}
}
组件:
class AllPatient extends Component {
_isMounted = false;
state ={
isLoading: true
}
_changeHandler = (e) => {
let data = {...this.state}
data[e.target.name] = e.target.value
this.setState(data)
}
componentDidMount = () =>{
this._isMounted = true;
this.props.getPatients()
}
componentWillUnmount = () =>{
this._isMounted = false;
this.unsubscribe();
}
render() {
console.log(this.props)
let {patients} = this.props.patients
console.log(patients)
return (
<div>
<Container>
<SearchPatients change={this._changeHandler} />
{(this.props.patients.isLoading) ? <Loading /> :
<Card>
<Card.Body>
<Card.Title>
All Patients
</Card.Title>
<Table responsive>
<thead>
<tr>
<th>#</th>
<th>Full Name</th>
<th>Phone</th>
<th>DOB</th>
<th>Email</th>
<th>Last Visit</th>
</tr>
</thead>
<tbody>
{patients.patients.map(patient =>
<PatientList key={patient._id} patient={patient}/>
)}
</tbody>
</Table>
</Card.Body>
</Card>}
</Container>
</div>
)
}
}
const mapStateToProps = (state) =>{
console.log(state)
return {
patients : state.patients,//.patients.patients,
// isLoading : state.isLoading
}
}
const mapDispatchToProps = (dispatch) =>{
return {
getPatients : () => dispatch(getAllPatients())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(AllPatient)
操作:
export const getAllPatients = () => async (dispatch) => {
let token = getToken()
if(token){
try{
const response = await axios.get(`${baseUrl}/api/patients`,headerInfo,{cancelToken: source.token})
return dispatch({
type : ALL_PATIENT_SUCCESS,
payload: response.data
})
}catch(e){
console.log(e)
return dispatch({
type : ALL_PATIENT_ERROR,
payload: e.response
})
}
}else{
console.log('error')
}
}