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

Next.js项目刷新时出现Cannot set properties of null (setting 'innerHTML')错误

问题描述

我正在开发一个从指定URL获取数据并展示到前端的网站,后续功能尚未实现。当前遇到的问题:直接加载localhost:3000时网站运行正常,但打开Chrome浏览器内置开发者工具后刷新页面,会抛出**"Cannot set properties of null (setting 'innerHTML')"**错误。我已尝试重构代码并排查可能的出错点,但仍未解决该问题。

代码示例

import Head from "next/head";
import styles from "@/styles/Home.module.css";
import { Inter } from "next/font/google";

import dynamic from "next/dynamic";
const inter = Inter({ subsets: ["latin"] });
let foundationUrl = "https://api.binance.us/api/v3/ticker/price?symbol=";

function createPriceFed(foundationUrl, ticker1, ticker2) {
  var url = foundationUrl + ticker1 + ticker2;
  return url;
}

async function btcPriceFeed() {
  var url = createPriceFed(foundationUrl, "BTC", "USD");
  let response = await fetch(url);
  if (response.ok) {
    let json = await response.json();
    let priceData = json["symbol"] + " : " + json["price"];
    if (
      typeof document != "undefined" &&
      typeof document != "[object Object]"
    ) {
      let priceContainer = document.querySelector("#btc");
      priceContainer.innerHTML = priceData;
    }
  } else {
    alert("HTTP-Error " + response.text);
  }
  setTimeout(btcPriceFeed, 5000);
}

async function ethPriceFeed() {
  var url = createPriceFed(foundationUrl, "ETH", "USD");
  let response = await fetch(url);
  if (response.ok) {
    let json = await response.json();
    let priceData = json["symbol"] + " : " + json["price"];
    if (
      typeof document != "undefined" &&
      typeof document != "[object Object]"
    ) {
      let priceContainer = document.querySelector("#eth");
      priceContainer.innerHTML = priceData;
    }
  } else {
    alert("HTTP-Error " + response.text);
  }
  setTimeout(ethPriceFeed, 5000);
}

async function lrcPriceFeed() {
  var url = createPriceFed(foundationUrl, "LRC", "USDT");
  let response = await fetch(url);
  if (response.ok) {
    let json = await response.json();
    let priceData = json["symbol"] + " : " + json["price"];
    if (
      typeof document != "undefined" &&
      typeof document != "[object Object]"
    ) {
      let priceContainer = document.querySelector("#lrc");
      priceContainer.innerHTML = priceData;
    }
  } else {
    alert("HTTP-Error " + response.text);
  }
  setTimeout(lrcPriceFeed, 5000);
}

const Home = () => {
  return (
    <>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <div id="btc" className="btc"></div>
      <div id="eth"></div>
      <div id="lrc"></div>
      
    </>
  );
};

export default dynamic(() => Promise.resolve(Home), { ssr: false });

btcPriceFeed();
ethPriceFeed();
lrcPriceFeed();

相关截图

  • 未打开开发者工具时网站运行状态:
    未打开开发者工具时网站运行状态
  • 打开开发者工具刷新后的报错状态:
    打开开发者工具刷新后的报错状态
解决方案

问题根源

你直接在模块顶层调用btcPriceFeed()、ethPriceFeed()、lrcPriceFeed(),这些函数会在组件渲染完成前就执行。你加的DOM存在性判断逻辑错误:typeof document返回的是"object",typeof document != "[object Object]"这个条件永远成立,导致代码会强制尝试获取DOM元素。而打开开发者工具刷新时,浏览器渲染节奏变化,此时DOM元素还未挂载,document.querySelector返回null,自然触发设置innerHTML的错误。

修复步骤

  1. 移除错误的DOM存在性判断,只保留typeof document !== "undefined"即可。
  2. 把数据获取逻辑放到组件的useEffect钩子中,确保组件挂载后再操作DOM。
  3. 组件卸载时清理定时器,避免内存泄漏。

修复后的代码

import Head from "next/head";
import styles from "@/styles/Home.module.css";
import { Inter } from "next/font/google";
import { useEffect, useRef } from "react";

const inter = Inter({ subsets: ["latin"] });
const foundationUrl = "https://api.binance.us/api/v3/ticker/price?symbol=";

function createPriceFed(foundationUrl, ticker1, ticker2) {
  return `${foundationUrl}${ticker1}${ticker2}`;
}

async function fetchPrice(tickerPair, elementId) {
  const url = createPriceFed(foundationUrl, ...tickerPair);
  try {
    const response = await fetch(url);
    if (!response.ok) throw new Error(`HTTP-Error ${response.status}`);
    const json = await response.json();
    const priceData = `${json.symbol} : ${json.price}`;
    
    if (typeof document !== "undefined") {
      const priceContainer = document.querySelector(`#${elementId}`);
      if (priceContainer) {
        priceContainer.innerHTML = priceData;
      }
    }
  } catch (error) {
    alert(error.message);
  }
}

const Home = () => {
  const timersRef = useRef([]);

  useEffect(() => {
    const updateBtc = () => {
      fetchPrice(["BTC", "USD"], "btc");
      timersRef.current.push(setTimeout(updateBtc, 5000));
    };
    const updateEth = () => {
      fetchPrice(["ETH", "USD"], "eth");
      timersRef.current.push(setTimeout(updateEth, 5000));
    };
    const updateLrc = () => {
      fetchPrice(["LRC", "USDT"], "lrc");
      timersRef.current.push(setTimeout(updateLrc, 5000));
    };

    updateBtc();
    updateEth();
    updateLrc();

    return () => {
      timersRef.current.forEach(timer => clearTimeout(timer));
    };
  }, []);

  return (
    <>
      <Head>
        <title>Crypto Price Feed</title>
        <meta name="description" content="Real-time crypto price feed from Binance US" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <div id="btc" className="btc"></div>
      <div id="eth"></div>
      <div id="lrc"></div>
    </>
  );
};

export default Home;

额外优化说明

  • 提取了重复的fetchPrice函数,减少代码冗余。
  • 用useRef存储定时器ID,确保组件卸载时能彻底清理。
  • 添加了DOM元素存在性判断,进一步规避空指针风险。
  • 移除了不必要的dynamic导出,useEffect已确保逻辑在客户端执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:07:05