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

基于Clarifai的人脸检测React应用出现白屏死亡问题求助

解决Zero To Mastery人脸检测应用白屏问题

我跟着Zero To Mastery课程用JavaScript结合Clarifai做了个人脸检测应用,还根据Clarifai官网可访问的JavaScript REST配置更新了代码(官网部分页面显示‘Ooops, this page no longer exists’错误)。但每次运行都会碰到**白屏死亡(WHITE SCREEN OF DEATH)**的问题,求解决方案。

完整App.js代码

import React, {Component} from 'react';
import Clarifai from 'clarifai';
import ParticlesBg from 'particles-bg'
import Navigation from './components/Navigation/Navigation';
import Logo from './components/Logo/Logo';
import Rank from './components/Rank/Rank';
import ImageLinkForm from './components/ImageLinkForm/ImageLinkForm';
import FaceRecognition from './components/FaceRecognition/FaceRecognition';
import './App.css';

const PAT = '6ff576691c034b2da140922bf0f1fb0e';
const USER_ID = 'tybyers21';       
const APP_ID = 'Face-Detector';
const MODEL_ID = 'face-detection';
const MODEL_VERSION_ID = '6dc7e46bc9124c5c8824be4822abe105';    
const IMAGE_URL = 'https://samples.clarifai.com/metro-north.jpg';

const app = new Clarifai.App({
 apiKey: '057657601d694b899ded85a360495f0b'
});

const raw = JSON.stringify({
    "user_app_id": {
        "user_id": USER_ID,
        "app_id": APP_ID
    },
    "inputs": [
        {
            "data": {
                "image": {
                    "url": IMAGE_URL
                }
            }
        }
    ]
});

const requestOptions = {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Authorization': 'Key ' + PAT
    },
    body: raw
};

fetch("https://api.clarifai.com/v2/models/" + MODEL_ID + "/versions/" + MODEL_VERSION_ID + "/outputs", requestOptions)
    .then(response => response.text())
    .then(result => console.log(result))
.catch(error => console.log('error', error));


class App extends Component {
 constructor() {
   super();
   this.state = {
     input: '',
     imageUrl: '',
     box: {},
}
 }

onInputChange = (event) => {
 this.setState({input: event.target.value})
}

calculateFaceLocation = (data) => {
 const clarifaiFace = data.outputs[0].data.regions[0].region_info.bounding_box;
 const image = document.getElementById('inputimage');
 const width = Number(image.width);
 const height = Number(image.height);
 return {
   leftCol: clarifaiFace.left_col *width,
   topRow: clarifaiFace.top_row * height,
   rightCol: width - (clarifaiFace.right_col * width),
   bottomRow: height - (clarifaiFace.bottom_rol * height)
 }
}

displayFaceBox = (box) => {
    this.setState({box: box});
}

onButtonSubmit = () => {
 this.setState=({imageUrl: this.state.input});
      app.models.predict({
        id: "a403429f2ddf4b49b307e318f00e528b",
        version: "6dc7e46bc9124c5c8824be4822abe105",
      },
   this.state.input)
       .then(response => this.displayFaceBox(this.calculateFaceLocation(response)))
       .catch(err => console.log(err));
}
 render() {
   return (

     <div className="App">
       <ParticlesBg num={400} type="cobweb" bg={true} />
       <Navigation />
       <Logo />
       <Rank />
       <ImageLinkForm 
       onInputChange={this.onInputChange} 
       onButtonSubmit={this.onButtonSubmit} />
       <FaceRecognition box={this.state.box} imageUrl={this.state.imageUrl}/>
     </div>
 );
}
}

export default App;

问题排查与解决方案

1. 修复代码中的语法错误

  • setState语法错误:onButtonSubmit方法里的this.setState=({imageUrl: this.state.input});多了一个等号,正确写法是this.setState({imageUrl: this.state.input});,错误写法会覆盖React的setState方法,导致状态更新失败引发崩溃。
  • 拼写错误:calculateFaceLocation里的clarifaiFace.bottom_rol应为clarifaiFace.bottom_row,拼写错误会导致计算边界框时抛出undefined错误。
  • 外部fetch请求:将fetch请求直接写在组件外部,会在组件初始化前执行,若请求出错会直接导致应用崩溃。建议移除该冗余请求(你已经在组件内使用Clarifai SDK发起请求),或移到组件生命周期方法(如componentDidMount)内。

2. 修正后的代码示例

import React, {Component} from 'react';
import Clarifai from 'clarifai';
import ParticlesBg from 'particles-bg'
import Navigation from './components/Navigation/Navigation';
import Logo from './components/Logo/Logo';
import Rank from './components/Rank/Rank';
import ImageLinkForm from './components/ImageLinkForm/ImageLinkForm';
import FaceRecognition from './components/FaceRecognition/FaceRecognition';
import './App.css';

// 初始化Clarifai SDK
const app = new Clarifai.App({
  apiKey: '057657601d694b899ded85a360495f0b'
});

class App extends Component {
  constructor() {
    super();
    this.state = {
      input: '',
      imageUrl: '',
      box: {},
    }
  }

  onInputChange = (event) => {
    this.setState({input: event.target.value})
  }

  calculateFaceLocation = (data) => {
    const clarifaiFace = data.outputs[0].data.regions[0].region_info.bounding_box;
    const image = document.getElementById('inputimage');
    const width = Number(image.width);
    const height = Number(image.height);
    return {
      leftCol: clarifaiFace.left_col * width,
      topRow: clarifaiFace.top_row * height,
      rightCol: width - (clarifaiFace.right_col * width),
      bottomRow: height - (clarifaiFace.bottom_row * height) // 修正拼写错误
    }
  }

  displayFaceBox = (box) => {
    this.setState({box: box});
  }

  onButtonSubmit = () => {
    this.setState({imageUrl: this.state.input}); // 修正setState语法
    app.models.predict({
      id: "a403429f2ddf4b49b307e318f00e528b",
      version: "6dc7e46bc9124c5c8824be4822abe105",
    }, this.state.input)
    .then(response => this.displayFaceBox(this.calculateFaceLocation(response)))
    .catch(err => {
      console.log(err);
      // 添加错误提示,避免静默崩溃
      alert('人脸检测失败,请检查图片链接或API密钥');
    });
  }

  render() {
    return (
      <div className="App">
        <ParticlesBg num={400} type="cobweb" bg={true} />
        <Navigation />
        <Logo />
        <Rank />
        <ImageLinkForm 
          onInputChange={this.onInputChange} 
          onButtonSubmit={this.onButtonSubmit} />
        <FaceRecognition box={this.state.box} imageUrl={this.state.imageUrl}/>
      </div>
    );
  }
}

export default App;

3. 额外排查建议

  • 查看浏览器控制台:按F12打开开发者工具,查看Console标签的错误信息,这是定位白屏问题的核心依据(比如API请求失败、组件渲染错误等)。
  • 验证API权限:确认Clarifai API密钥有效,且具备访问face-detection模型的权限,避免因权限问题引发请求失败。
  • 检查依赖版本兼容性:确认Clarifai SDK、ParticlesBg与当前React版本兼容,版本不匹配可能导致运行时错误。
  • 添加错误边界:给组件添加错误边界,捕获子组件的异常,避免整个应用崩溃白屏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 06:51:53