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

React Native进度条达100%时报错:_this2.state.progress不是函数

问题修复:进度条到100%时报错且无法正常显示

错误原因

报错ERROR: _this2.state.progress is not a function的直接原因是你在代码里错误地把this.state.progress(数值类型的进度值)当成函数调用了:

else {
  this.state.progress(false); // 这里完全错误,progress是数值不是函数
}

另外进度卡在99%是因为进度超过100时没有正确修正数值,也没停止定时器,导致逻辑混乱。

修复步骤及代码

  1. 保存定时器引用,方便进度完成后清除,防止内存泄漏
  2. 修正进度超过100时的逻辑:将进度设为100,然后清除定时器
  3. 初始化state时补充indeterminate字段,避免undefined

修复后的完整代码:

import React, { Component } from 'react';
import { StyleSheet, View, Text, Button } from 'react-native';
import * as Progress from 'react-native-progress';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      progress: 0,
      indeterminate: false // 初始化indeterminate字段
    };
    this.progressInterval = null; // 保存定时器引用
  }

  startProgressIndicators() {
    let progress = 0;
    this.setState({ progress }, () =>
      setTimeout(() => {
        this.setState({ indeterminate: false });
        // 保存定时器到实例变量
        this.progressInterval = setInterval(() => {
          progress += Math.random();
          if (progress >= 100) {
            progress = 100; // 进度超过100时强制设为100
            clearInterval(this.progressInterval); // 清除定时器,停止累加
          }
          this.setState({ progress });
        }, 500);
      }, 1500)
    );
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.text}>indicador de progresso</Text>
        <View style={{ margin: 5 }} />

        <Button
          title="Iniciar"
          onPress={() => this.startProgressIndicators()}
        />

        <View style={{}}> {/* 修正笔误:styles改为style */}
          <Text>{`${this.state.progress.toFixed(0)}%`}</Text>
        </View>

        <Progress.Bar
          size={50}
          progress={this.state.progress / 100}
          width={200}
          style={{ margin: 5, fontSize: 10 }}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    color: '#051923',
    margin: 10,
    fontSize: 30,
  },
});

export default App;

额外修正点

  • 修复了render里View组件的属性错误:把styles={{}}改成style={{}},避免样式不生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:01:12