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

React.js报错Uncaught ReferenceError: state is not defined排查

问题诊断

你遇到的Uncaught ReferenceError: state is not defined报错和样式失效问题,由以下几处代码错误直接导致:

  • state访问语法错误:类组件状态挂载在实例this下,你在shapeStyle里写的{this:state.bgColour}属于完全无效的语法,直接写state会被JS识别为未定义的全局变量,直接抛出引用错误。
  • 样式值缺少单位:CSS的width/height需要长度单位(这里用px即可),border-radius的百分比值需要带%后缀,你生成的随机值是纯数字,没有拼接单位时浏览器无法解析对应样式。
  • 静态样式冲突:你给挂载节点.shape-item写死了宽高、蓝色背景、50%圆角的CSS规则,会和组件动态生成的内联样式冲突,出现保留样式代码仅渲染基础形状的问题。
  • 渲染逻辑错误:你在JSX中直接写{this.state.shape}试图渲染一个JS对象,React不支持直接渲染普通对象,会触发额外报错;同时你先后两次调用ReactDOM.render挂载内容,第二次调用会直接覆盖第一次的渲染结果,属于冗余无效代码。
修复后的完整代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Timed Shapes</title>
    <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> 
    <style>
        /* 移除容器上和形状相关的固定样式,避免样式冲突 */
        #shape-container{
            padding: 20px;
        }
    </style>
</head>
<body>
    <!-- 改用id作为挂载点,避免和组件类名冲突 -->
    <div id="shape-container"></div>

    <script type="text/babel">
        "use strict";
        var colours = ["#77b3d1", "#E94F37", "#1C89BF", "#A1D363", "#85FFC7", "#297373", "#FF8552", "#A40E4C", "#85AFC0", "#296573", "#AA8552", "#CC0E4C", "#567187", "#c6c976", "#967c64", "#e497ed", "#d24cff", "#e2ceb1", "#cc999e", "#97bf9a"];
        
        class Shapes extends React.Component{
            constructor(props){
                super(props);
                this.state = {
                    bgColour: colours[Math.floor((Math.random() * colours.length))],
                    size: 100,
                    perCent: 50
                }
            }

            componentDidMount(){
                this.timerID = setInterval(() => this.updateShape(), 1000);
            }

            componentWillUnmount(){
                clearInterval(this.timerID);
            }

            updateShape(){
                this.setState({
                    bgColour: colours[Math.floor((Math.random() * colours.length))],
                    // 加最小尺寸限制,避免形状太小不可见
                    size: Math.floor(Math.random() * 125) + 20,
                    perCent: Math.floor(Math.random() * 100)
                })
            }

            render(){
                // 正确访问this上的state,拼接对应样式单位
                const shapeStyle = {
                    padding: 10,
                    margin: 20,
                    display: 'inline-block',
                    backgroundColor: this.state.bgColour,
                    borderRadius: `${this.state.perCent}%`,
                    width: `${this.state.size}px`,
                    height: `${this.state.size}px`
                }
                // 移除直接渲染对象的错误逻辑
                return <div style={shapeStyle}></div>
            }
        }

        const shapesRender = [];
        for(let i=0; i < 60; i++){
            shapesRender.push(<Shapes key={i} />);
        }
        // 仅执行一次渲染
        ReactDOM.render(shapesRender, document.querySelector("#shape-container"));
    </script>
</body>
</html>
关键修改点说明
  • 修正state访问逻辑:去掉多余的shape嵌套层级,直接通过this.state.xxx访问对应状态,替换错误的对象语法。
  • 补全样式单位:尺寸值拼接px后缀,圆角值拼接%后缀,保证浏览器可以正常解析样式规则。
  • 解决样式冲突:删除挂载容器上写死的形状样式,改用独立id作为React挂载点,避免静态CSS覆盖动态样式。
  • 清理冗余逻辑:删除重复的ReactDOM.render调用,移除JSX中直接渲染state对象的错误代码,补充尺寸最小值限制避免形状不可见。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 09:27:31