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

Next.js项目中变量无赋值自动变更、组件重复渲染及console.log异常问题求助

问题分析与解决思路

Hey, let's break down what's happening here—this weird behavior is actually an intentional feature of Next.js in development mode, not a bug!

The Root Cause: React Strict Mode

Your Next.js 11.1.2 setup enables React Strict Mode by default in development. This mode is built to help you catch accidental side effects in your code by doing a few key things:

  • Running component render logic twice
  • Re-running useEffect callbacks (simulating an unmount followed by a remount to test cleanup logic)
  • Silencing some console logs from the first render to avoid overwhelming you with duplicate output (this is why you saw missing or mismatched logs!)

Why Your Original Logger Code Seemed Broken

Since your log instance is created outside the Chat component (at the module level), both renders share the same logger instance. When the component renders twice:

  1. First render: log('render') increments logId (triggers your getter/setter logs)
  2. Second render: log('render') increments it again
    But React hides the first render's console.log output, making it look like the logId changed without being accessed. The getter/setter was actually being called twice—you just couldn't see all the logs.

Why Your Updated Code Showed Two Render Entries

Your modified allLogs array captured both renders because it's not affected by React's log silencing. The duplicate entries confirm that Strict Mode is forcing the component to render twice, even though only one set of logs appears in the console by default.

How to Verify This

To confirm Strict Mode is the culprit, disable it in next.config.js:

module.exports = {
  reactStrictMode: false,
}

Restart your dev server, and you'll see the component only renders once, with all logs matching your initial expectations.

Should You Disable Strict Mode?

No—it's a valuable tool for catching bugs early! Instead, adjust your code to work with Strict Mode:

  • If you need a logger per component instance, move the createLogger call inside the component to ensure isolation:
// Updated Chat.tsx
import { useEffect } from 'react';
import { createLogger } from './logs';

export default function Chat(): JSX.Element {
  const log = createLogger({ name: 'Chat' }); // Instance-specific logger
  
  log('render');
  useEffect(() => {
    log('useEffect');
    // Add cleanup logic here if you have side effects (e.g., subscriptions)
  }, []);
  return <div>Some content</div>;
}
  • To see all logs in Strict Mode, go to your browser console settings, find the "Console" section, and check "Show all logs" or "Preserve log"—this will reveal the hidden first-render logs.

内容的提问来源于stack exchange,提问作者Ruslan Zhomir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 19:57:28