You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解决派发Redux属性更新时父组件渲染冲突报错问题

React报错:Cannot update a component while rendering a different component 修复求助

报错内容

Cannot update a component (GameBase) while rendering a different component (ExistingGame). To locate the bad setState() call inside...

业务场景

GameBase组件根据Redux中gameReducer.registered的值,条件渲染ExistingGame组件,核心逻辑代码如下:

if (gameReducer.registered){
    return(
        <>
            <ExistingGame />
            { goBackIcon }
        </>
    )   
}

gameReducer.registered的值由GameBase内列表的点击事件触发dispatch设置,列表组件代码:

const ActiveGameList = () => (
    <table><tbody>
      {activeGamesArray.map(activeGame => (
        // ...省略其他表格元素
        <td key={`join${activeGame.gameId}`} className="joinGame"> 
          <IconContext.Provider value={{ size:20 }}>
            <div className='joinGameIcon' onClick={()=>{ joinTheGame(activeGame) }}>
              <ImUserPlus />
            </div>
          </IconContext.Provider>
        </td>
        </tr>
      ))}
    </tbody></table>
);

return(
    <>
        <h1>Existing games</h1>
        <h3>Select game to join:</h3>
        <ActiveGameList />
        <br/>
        { goBackIcon }
    </>
)

核心逻辑函数

点击事件触发的joinTheGame函数实现:

const joinTheGame = async (activeGame) => {
    let gameInfo = {
        gameId:activeGame.gameId, 
        gameName: activeGame.gameName, 
        bankerPlayerNumber: activeGame.bankerPlayerNumber, 
        forename: activeGame.firstName, 
        surname: activeGame.lastName, 
        gameLive: activeGame.gameLive 
    };
    
    // 先获取选中游戏的玩家信息,再跳转对应组件
    await client.query({
        query: GAME_PLAYER_DETAILS,
        fetchPolicy: "network-only",
        variables: {gameId:gameInfo.gameId}
    })
    .then(result => {
        let players = result.data.allGameMoneyPlayers.nodes;
        gameInfo.players = players;

        if (joinLiveGame){
            dispatch(reJoinGame(gameInfo));  
        } else if (joinPendingGame){
            dispatch(joinGame(gameInfo));
        }
    });
}

遇到的困境

查阅资料得知这类“渲染时更新组件”的错误需要把状态变更调用放入useEffect钩子,但尝试在点击回调中使用useEffect时,触发了React Hook "useEffect" cannot be called inside a callback错误,求可行的解决方向。


内容的提问来源于stack exchange,提问作者Mr Davros

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 05:27:49