首页 > 解决方案 > TypeError:部署到 Netlify 后无法将类作为函数调用?

问题描述

您好,我正在尝试将 Web 应用程序部署到 Netlify。它在前端使用 COCO SSD 模型进行对象识别,这是有目的的。Web 应用程序在 localhost 上运行良好,但是一旦我部署到 Netlify,我就会收到此错误:

detector.js:47 TypeError: Cannot call a class as a function
    at r (classCallCheck.js:3)
    at new t (tensor.ts:266)
    at t.value (engine.ts:736)
    at i (tensor_ops_util.ts:75)
    at i (tensor.ts:55)
    at Module.p (io_utils.ts:223)
    at t.value (graph_model.ts:139)
    at t.<anonymous> (graph_model.ts:119)
    at c (runtime.js:63)
    at Generator._invoke (runtime.js:293)

我以前从来没有遇到过这个问题,觉得很奇怪,这是我实现COCO SSD模型和类的代码。

import React from 'react';
import Lottie from 'react-lottie';
import * as cocoSsd from '@tensorflow-models/coco-ssd';
import '@tensorflow/tfjs';

class Detector extends Component {
  constructor(props) {
    super(props);

    this.state = {
      count: 0,
      list: ['person','laptop','scissors','mouse', 'spoon', 'keyboard',],
      isStopped: true,
    }
  } 
  videoRef = React.createRef();

  componentDidMount() {
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
      //getting camera permission code removed for readability
      const modelPromise = cocoSsd.load();
      Promise.all([modelPromise, webCamPromise])
        .then(values => {
          this.detectFrame(this.videoRef.current, values[0]);
        })
        .catch(error => {
          console.error(error);
        });
    }
  }

  detectFrame = (video, model) => {
    model.detect(video).then(predictions => {
      this.checkPredictions(predictions);
      requestAnimationFrame(() => {
        this.detectFrame(video, model);
      });
    });
  };

  checkPredictions = predictions => {
    predictions.forEach(prediction => {
      if(prediction.class === this.state.list[0]) {
        const tempL = this.state.list;
        const tempC = this.state.count + 1;
        tempL.shift();
        this.setState({list: tempL, count: tempC, isStopped: false});
      }
    });
  };

  render() {
    return (
      <div>
        //removed for readability
      </div>
    );
  }
}

export default Detector;

标签: javascriptreactjstensorflownetlify

解决方案


看起来已经选择了最终问题的生产模式webpack的字段(构建文件) 。@tensorflow/tfjs

但我们可以手动指定此字段,此处描述https://webpack.js.org/configuration/resolve/#resolvemainfields

为了做到这一点,您只需切换到使用react-app-rewired我们可以自定义webpack配置的地方。以下是步骤:

  • 安装
npm i -D react-app-rewired
  • 在根仓库创建覆盖配置文件,config-overrides.js内容如下:
module.exports = function override(config, env) {
  if (process.env.NODE_ENV === 'production')
  {
    config.resolve.mainFields = ['main'];
  }
  return config;
}
  • react-app-rewired通过替换react-scripts命令切换到使用脚本:
"scripts": {
  "start": "react-app-rewired start",
  "build": "react-app-rewired build",
  // ...  
},

最后,您可以运行npm build并提供构建的内容以对其进行测试。就是这样!


推荐阅读