【发布时间】:2019-08-17 01:28:46
【问题描述】:
我正在使用最新版本的 ReactJS 并使用 Axios 发出请求。但在我输入cancel() 函数之前,我收到了以下错误:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
in MenuPlaylist (at Sidebar/index.js:19)
in aside (created by Context.Consumer)
in StyledComponent (created by styled.aside)
in styled.aside (at Sidebar/index.js:11)
in Sidebar (at Search/index.js:16)
in Search (created by Context.Consumer)
因为问题是组件一拆卸就泄漏了内存。但现在取消请求,我在控制台上收到以下消息:
取消请求以避免内存泄漏的正确方法是什么?
组件:
import React, { Component } from "react";
// STYLES
import { Menu, Title } from "./styles";
// SERVICES
import { cancelAxiosRequest, getAllPlaylist } from "services/Api";
// SUBCOMPONENT'S
import { CreatePlaylist, CreatedPlaylist } from "components";
class MenuPlaylist extends Component {
state = {
data: []
};
// LIFE CYCLES
componentDidMount() {
this.consumeAPI();
}
componentWillUnmount() {
cancelAxiosRequest("Request Canceled.");
}
// METHODS
consumeAPI = () => {
getAllPlaylist().then(({ data }) => {
this.setState({ data: data });
});
};
render = () => {
return (
<Menu>
<Title>PLAYLISTS</Title>
<CreatePlaylist />
<CreatedPlaylist data={this.state.data} />
</Menu>
);
};
}
export default MenuPlaylist;
AXIOS:
import axios from "axios";
const instance = axios.create({
baseURL: "http://localhost:3001",
timeout: 1000
});
let CancelToken = axios.CancelToken;
export let cancelAxiosRequest;
// GET'S
export function getNewReleases() {
return instance.get("/newReleases");
}
export function getAllPlaylist() {
return instance.get("/playlist", {
cancelToken: new CancelToken(function executor(c) {
cancelAxiosRequest = c;
})
});
}
export function getPlaylist(name) {
return instance.get("/playlist", {
params: {
name: name
}
});
}
// POST'S
export function postNewPlaylist(id, name) {
return instance.post("/playlist", {
id: id,
to: `/playlist/${id}`,
name: name
});
}
【问题讨论】: