Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react useEffect中调接口然后用useState设置值立即跳转到其他页面报Can't perform a React state update on an unmounted component. #93

Open
lizhongzhen11 opened this issue May 28, 2020 · 0 comments

Comments

@lizhongzhen11
Copy link
Owner

我用 React Hooks 开发的项目。

在设备列表页面时一进来要查该用户能看的项目,所以我是这样写的:

  useEffect(() => {
    findAll({
      userId: userId,
      iotOperator: props.iotOperator,
      type: props.type
    }).then(res => {
      setProjects(res.data.result.records)
    }).catch(err => {
      message.error('查询所有项目失败')
    })
  }, [])

开发时由于一直在这个页面,没有发现问题,但是同事测试时发现,一进这个页面没等 setProjects(res.data.result.records) 时就跳转到其他页面,就报错:
**Can't perform a React state update on an unmounted component. **

一开始觉得很纳闷,后来发现是 setProjects(res.data.result.records) 这里有问题,组件卸载了,但是之前是调接口异步去 setProjects(res.data.result.records) 的,对一个已经卸载的组件去设置state,当然有问题!

问题找到了,如何解决?这个问题倒困扰了我不少时间。

起初我寄希望于 React 官方有什么api能限制,去github 的issue上搜了下,不少跟我相似的问题,后来在 facebook/react#15006 这里找到解决方法,方法很简单,但是我没想到。。。

加个标识符就好了:

  useEffect(() => {
    let isMounted = true // 标识该组件是否被挂在
    findAll({
      userId: userId,
      iotOperator: props.iotOperator,
      type: props.type
    }).then(res => {
      isMounted && setProjects(res.data.result.records)
    }).catch(err => {
      message.error('查询所有项目失败')
    })

    return () => {
      isMounted = false
    }
  }, [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant