我认为标题说明了一切。每次卸载仍在提取的组件时都会显示黄色警告。
Console警告:无法在未安装的组件上调用
setState
(或forceUpdate
)。这是一个无操作,但是......要修复,取消componentWillUnmount
方法中的所有订阅和异步任务。
constructor(props){
super(props);
this.state = {
isLoading: true,
dataSource: [{
name: 'loading...',
id: 'loading',
}]
}
}
componentDidMount(){
return fetch('LINK HERE')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
当您触发Promise时,它可能需要几秒钟才能结算,到那时用户可能已导航到您应用中的其他位置。因此,当Promise解析setState
在未安装的组件上执行时,您会收到错误 - 就像您的情况一样。这也可能导致内存泄漏。
这就是为什么最好将一些异步逻辑从组件中移出。
否则,你需要以某种方式cancel your Promise。或者 - 作为最后的手段技术(它是反模式) - 你可以保留一个变量来检查组件是否仍然被挂载:
componentDidMount(){
this.mounted = true;
this.props.fetchData().then((response) => {
if(this.mounted) {
this.setState({ data: response })
}
})
}
componentWillUnmount(){
this.mounted = false;
}
我会再强调一下 - 这个is an antipattern但在你的情况下可能就足够了(就像他们用Formik
实现的那样)。
关于GitHub的类似讨论
编辑:
这可能是我如何用Hooks解决同样的问题(只有React):
选项A:
import React, { useState, useEffect } from "react";
export default function Page() {
const value = usePromise("https://something.com/api/");
return (
<p>{value ? value : "fetching data..."}</p>
);
}
function usePromise(url) {
const [value, setState] = useState(null);
useEffect(() => {
let isMounted = true; // track whether component is mounted
request.get(url)
.then(result => {
if (isMounted) {
setState(result);
}
});
return () => {
// clean up
isMounted = false;
};
}, []); // only on "didMount"
return value;
}
选项B:或者使用useRef
,其行为类似于类的静态属性,这意味着当值的变化时它不会使组件重新呈现:
function usePromise2(url) {
const isMounted = React.useRef(true)
const [value, setState] = useState(null);
useEffect(() => {
return () => {
isMounted.current = false;
};
}, []);
useEffect(() => {
request.get(url)
.then(result => {
if (isMounted.current) {
setState(result);
}
});
}, []);
return value;
}
// or extract it to custom hook:
function useIsMounted() {
const isMounted = React.useRef(true)
useEffect(() => {
return () => {
isMounted.current = false;
};
}, []);
return isMounted; // returning "isMounted.current" wouldn't work because we would return unmutable primitive
}
React recommend的友好人员将你的取消电话/承诺包含在可取消的承诺中。虽然该文档中没有建议使用fetch将代码与类或函数分开,但这似乎是可取的,因为其他类和函数可能需要此功能,代码重复是反模式,并且无论延迟代码如何应在componentWillUnmount()
处理或取消。根据React,您可以在cancel()
中的包装承诺上调用componentWillUnmount
,以避免在未安装的组件上设置状态。
如果我们使用React作为指南,提供的代码看起来就像这些代码片段:
const makeCancelable = (promise) => {
let hasCanceled_ = false;
const wrappedPromise = new Promise((resolve, reject) => {
promise.then(
val => hasCanceled_ ? reject({isCanceled: true}) : resolve(val),
error => hasCanceled_ ? reject({isCanceled: true}) : reject(error)
);
});
return {
promise: wrappedPromise,
cancel() {
hasCanceled_ = true;
},
};
};
const cancelablePromise = makeCancelable(fetch('LINK HERE'));
constructor(props){
super(props);
this.state = {
isLoading: true,
dataSource: [{
name: 'loading...',
id: 'loading',
}]
}
}
componentDidMount(){
cancelablePromise.
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson,
}, () => {
});
})
.catch((error) =>{
console.error(error);
});
}
componentWillUnmount() {
cancelablePromise.cancel();
}
----编辑----
通过在GitHub上关注问题,我发现给定的答案可能不太正确。这是我使用的一个版本,它适用于我的目的:
export const makeCancelableFunction = (fn) => {
let hasCanceled = false;
return {
promise: (val) => new Promise((resolve, reject) => {
if (hasCanceled) {
fn = null;
} else {
fn(val);
resolve(val);
}
}),
cancel() {
hasCanceled = true;
}
};
};
这个想法是通过使函数或任何你使用null的东西来帮助垃圾收集器释放内存。
您可以使用AbortController取消获取请求。
class FetchComponent extends React.Component{
state = { todos: [] };
controller = new AbortController();
componentDidMount(){
fetch('https://jsonplaceholder.typicode.com/todos',{
signal: this.controller.signal
})
.then(res => res.json())
.then(todos => this.setState({ todos }))
.catch(e => alert(e.message));
}
componentWillUnmount(){
this.controller.abort();
}
render(){
return null;
}
}
class App extends React.Component{
state = { fetch: true };
componentDidMount(){
this.setState({ fetch: false });
}
render(){
return this.state.fetch && <FetchComponent/>
}
}
ReactDOM.render(<App/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
由于帖子已经打开,因此添加了“abortable-fetch”。 qazxsw poi
(来自文档:)
控制器+信号机动满足AbortController和AbortSignal:
https://developers.google.com/web/updates/2017/09/abortable-fetch
控制器只有一种方法:
controller.abort();执行此操作时,它会通知信号:
const controller = new AbortController();
const signal = controller.signal;
这个API由DOM标准提供,这就是整个API。它是故意通用的,因此可以被其他Web标准和JavaScript库使用。
例如,以下是您在5秒后进行提取超时的方法:
signal.addEventListener('abort', () => {
// Logs true:
console.log(signal.aborted);
});
当我需要“取消所有订阅和异步”时,我通常会在componentWillUnmount中向redux发送一些内容,以通知所有其他订阅者,并在必要时向服务器发送一个有关取消的请求
这个警告的关键在于你的组件引用了一些由一些出色的回调/承诺保留的引用。
为避免反模式保持你的isMounted状态(使你的组件保持活着),就像在第二种模式中所做的那样,反应网站建议使用const controller = new AbortController();
const signal = controller.signal;
setTimeout(() => controller.abort(), 5000);
fetch(url, { signal }).then(response => {
return response.text();
}).then(text => {
console.log(text);
});
;但是,该代码似乎也可以使您的对象保持活力。
相反,我通过使用带有嵌套绑定函数的闭包来完成它。
这是我的构造函数(打字稿)......
using an optional promise
我想我找到了解决方法。问题不在于获取本身,而是在组件被解除后的setState。所以解决方案是将constructor(props: any, context?: any) {
super(props, context);
let cancellable = {
// it's important that this is one level down, so we can drop the
// reference to the entire object by setting it to undefined.
setState: this.setState.bind(this)
};
this.componentDidMount = async () => {
let result = await fetch(…);
// ideally we'd like optional chaining
// cancellable.setState?.({ url: result || '' });
cancellable.setState && cancellable.setState({ url: result || '' });
}
this.componentWillUnmount = () => {
cancellable.setState = undefined; // drop all references.
}
}
设置为this.state.isMounted
,然后在false
上将其更改为true,并在componentWillMount
中再次设置为false。然后只需componentWillUnmount
fetch中的setState。像这样:
if(this.state.isMounted)