You need to enable JavaScript to run this app. 如何在useEffect清理函数中取消异步任务解决React FlatList状态更新报错
优惠活动
大模型
产品
解决方案
定价
更多

如何在useEffect清理函数中取消异步任务解决React FlatList状态更新报错

问题根因

你触发该警告的核心原因有两点:

  1. 将Item组件嵌套定义在ChampSelect内部,父组件每次重渲染都会生成全新的Item实例,导致FlatList强制重渲染所有列表项,页面跳转、组件卸载后,未完成的渲染/图片加载任务结束后尝试更新状态就会触发警告
  2. 没有对组件挂载状态做校验,组件卸载后仍然执行状态更新操作

修复方案

1. 调整组件定义位置

将Item组件移出ChampSelect组件外部,避免嵌套组件重复创建引发的无效重渲染。

2. 新增挂载状态校验

用useRef存储组件挂载标记,所有状态更新前先判断组件是否处于挂载状态。

3. 优化图片加载逻辑

React Native 不支持require中使用动态拼接路径,建议预定义所有英雄图片的引用映射,避免图片加载异常。

4. FlatList 性能优化

添加removeClippedSubviews={true}属性,自动卸载非可视区域的列表项,减少后台无效加载任务。

修复后代码示例

import { useRef, useEffect, useState } from 'react'
// 其他导入省略

// 预定义英雄图片映射,替换成你的实际英雄列表
const champImages = {
  ahri: require('../pictures/champions/ahri.png'),
  garen: require('../pictures/champions/garen.png'),
  // 其余英雄图片依次添加
}

// Item组件移到外部定义
const Item = ({ item, onPress, weight, color}) => (
  <TouchableOpacity onPress={onPress}>
    <Image 
      source={champImages[item]}
      style={[styles.image, color]}
    />
    <Text style={[styles.title, weight]}>
      {item}
    </Text>
  </TouchableOpacity>    
)

function ChampSelect({navigation, route}) {
  const isMounted = useRef(true)
  const [selectedChamp, setSelectedChamp] = useState('')
  const [data, setData] = useState([])
  // 其余状态定义省略

  useEffect(() => {
    // 组件卸载时更新挂载标记
    return () => {
      isMounted.current = false
    }
  }, [])

  // 若有异步获取列表数据的逻辑,更新前先校验挂载状态
  const fetchChampList = async () => {
    const res = await yourApi.getChampList()
    if (isMounted.current) {
      setData(res)
    }
  }

  const renderItem = ({ item }) => {
    const fontWeight = item === selectedChamp ? 'bold' :'normal'
    const borderColor = item === selectedChamp ? '#6BDB5A' :'black'

    return (
      <Item 
        item={item}
        onPress={() => {
          // 更新状态前校验挂载状态
          if (isMounted.current) {
            setSelectedChamp(item)
          }
          // 如果点击后需要跳转页面,可在此处添加逻辑
        }}
        weight={{ fontWeight }}
        color={{borderColor}}
      />
    )
  }

  return ( 
    <View>
      {/* 其余布局代码省略 */}
      <View style={{marginLeft: 48, marginTop: 40}}>
        <FlatList
          ListHeaderComponent={renderHeader}
          numColumns={3}
          horizontal={false}
          data={data}
          extraData={selectedChamp}
          renderItem={renderItem}
          keyExtractor={item => item}
          removeClippedSubviews={true}
        />
      </View>
    </View>
  )
}

内容的提问来源于stack exchange,提问作者cel-0207

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 18:54:03