无法在 reactjs 中对未安装的组件执行 React 状态更新

Can't perform a React state update on an unmounted component in reactjs

我在 nextjs 中工作并覆盖了 _app.js 以便在所有 pages.I 中显示 header 已将 header 放置在布局中并在 [=19= 中使用它].in header 有搜索 bar.on 搜索,搜索结果必须从 header.Api 发送到其他组件工作正常但 returns 低于警告

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.

constant.js

export var searchKey = "";
export const setSearchKey = (value) => {
    searchKey = value;
}
export const getSearchKey = (value) => {
    return searchKey;
}

header.js

import * as searchConst from '../../static/constants/constants';

class HeaderComponent extends Component {
    state = {
        authType: true
    }

    componentDidMount() {
        Router.events.on('routeChangeComplete', this.routeChangeHandler);
    }

    routeChangeHandler(url) {
        url === '/appUser' ? this.setState({authType: true}) : this.setState({authType: false})
    }

    onSearch(event) {

        ApiService.onSearchUsers(0, this.state.authType, document.getElementById('search-input').value).then(res => {
            console.log(res);
            searchConst.setSearchKey(document.getElementById('search-input').value); //if i remove this line then there is no warning

            this.props.parentCallBack(userdata);

        });
    }

    render() {
        return (
            <div className="search-col">
                <Input id="search-input" className="text-box" placeholder="Enter name or Email.."
                       onKeyDown={($event) => this.onSearch($event)}
                       prefix={<Icon type="search" onClick={() => this.onSearch}></Icon>}></Input>
            </div>
        )
    }
}

出现警告是因为您正在设置组件安装状态。如果由于某种原因组件在状态更新之前被卸载,您将收到警告。避免警告的一种方法是在 componentWillUnmount 中将 mounted 状态设置为 false 并在修改状态之前检查它:

  state = {
    authType: true,
    mounted: true
  }

  componentDidMount() {
    Router.events.on('routeChangeComplete', this.routeChangeHandler);
  }

  componentWillUnmount() {
    setState({
      mounted: false
    });
  }

  routeChangeHandler(url) {
    if (mounted) {
      this.setState({
        authType: url === '/appUser'
      })
    }
  }