programing

Uncaughed Error: 크로스 오리진 오류가 발생하였습니다.React는 개발 중인 실제 오류 개체에 액세스할 수 없습니다.

easyjava 2023. 3. 5. 10:30
반응형

Uncaughed Error: 크로스 오리진 오류가 발생하였습니다.React는 개발 중인 실제 오류 개체에 액세스할 수 없습니다.

존을 송신할 때마다, 다음의 에러가 표시됩니다.

'잡히지 않은 오류: 교차원 오류가 발생했습니다.React는 개발 중인 실제 오류 개체에 액세스할 수 없습니다.'

이전 상태가 새 상태로 변경되었을 때 발생하는 Submit Zone 버튼을 눌렀을 때만 발생합니다. (this.setState)

Create Zone.js

import React, { Component } from "react";

export default class CreateZone extends Component {
  constructor(props) {
    super(props);
    this.state = {
      zone: {
        name: "",
        zipCode: "",
      },
    };
  }

  updateZone(event) {
    let updated = Object.assign({}, this.state.zone);
    updated[event.target.id] = event.target.value;
    this.setState({
      zone: updated,
    });
  }

  submitZone(event) {
    console.log("SubmitZone: " + JSON.stringify(this.state.zone));
    this.props.onCreate(this.state.zone);
  }

  render() {
    return (
      <div>
        <input
          onChange={this.updateZone.bind(this)}
          className="form-control"
          id="name"
          type="text"
          placeholder="Name"
        />{" "}
        <br />
        <input
          onChange={this.updateZone.bind(this)}
          className="form-control"
          id="zipCode"
          type="text"
          placeholder="Zip Code"
        />{" "}
        <br />
        <input
          onClick={this.submitZone.bind(this)}
          className="btn btn-danger"
          type="submit"
          value="Submit Zone"
        />
      </div>
    );
  }
}

Zones.js

import React, { Component } from "react";
import superagent from "superagent";
import { CreateZone, Zone } from "../presentation";

export default class Zones extends Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
    };
  }

  componentDidMount() {
    console.log("componentDidMount");
    superagent
      .get("/api/zone")
      .query(null)
      .set("Accept", "application/json")
      .end((err, response) => {
        if (err) {
          alert("ERROR: " + err);
          return;
        }
        console.log(JSON.stringify(response.body));
        let results = response.body.results;
        this.setState({
          list: results,
        });
      });
  }

  addZone(zone) {
    let updatedZone = Object.assign({}, zone);
    updatedZone["zipCodes"] = updatedZone.zipCode.split(",");
    console.log("ADD ZONE: " + JSON.stringify(updatedZone));

    superagent
      .post("/api/zone")
      .send(updatedZone)
      .set("Accept", "application/json")
      .end((err, response) => {
        if (err) {
          alert("ERROR: " + err.message);
          return;
        }
        console.log("ZONE CREATED: " + JSON.stringify(response));
        let updatedList = Object.assign([], this.state.list);
        updatedList.push(response.result);
        this.setState({
          list: updatedList,
        });
      });
  }

  render() {
    const listItems = this.state.list.map((zone, i) => {
      return (
        <li key={i}>
          {" "}
          <Zone currentZone={zone} />{" "}
        </li>
      );
    });

    return (
      <div>
        <ol>{listItems}</ol>
        <CreateZone onCreate={this.addZone.bind(this)} />
      </div>
    );
  }
}

Zone.js

import React, { Component } from "react";

import styles from "./styles";

export default class Zone extends Component {
  render() {
    const zoneStyle = styles.zone;

    return (
      <div style={zoneStyle.container}>
        <h2 style={zoneStyle.header}>
          <a style={zoneStyle.title} href="#">
            {" "}
            {this.props.currentZone.name}{" "}
          </a>
        </h2>
        <span className="detail"> {this.props.currentZone.zipCodes} </span>{" "}
        <br />
        <span className="detail">
          {" "}
          {this.props.currentZone.numComments} comments{" "}
        </span>
      </div>
    );
  }
}

에러를 해결하기 위해서, 저도 자주 이 에러가 발생합니다. 개발 도구 2를 엽니다. Application 섹션 3으로 이동합니다. 로컬 스토리지를 마우스 오른쪽 버튼으로 클릭하여 지웁니다.

오류가 해결되기를 바랍니다.

는, 에 발생하고 있었습니다.JSON.parse()★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

(편집: Chrome에만 있는 것 같습니다.FF는 해석 오류를 발생시킵니다.주석 참조)

리액트는 JSON.parse()가 비활성 문자열을 수신할 때마다 크로스 오리진 오류를 발생시킵니다.JSON 구조는 형식에 엄격하므로 저장 중인 JSON 값의 유효성을 확인합니다.

저는 사이트 데이터를 클리어하고 정상적으로 동작하고 있습니다.

저도 이 에러가 났어요.localStorage를 클리어하면 오류가 사라집니다.

  1. 개발자 도구에서 콘솔을 엽니다.
  2. 응용 프로그램 탭을 찾습니다.
  3. 로컬 스토리지를 찾습니다.
  4. 로케일 스토리지를 오른쪽 클릭하고 clear를 클릭하여 콘솔을 클리어합니다.

이것은 CORS 문제가 아닙니다.일반적으로 함수를 호출하는 데 문제가 있습니다.이 줄을 체크하다

this.props.onCreate(this.state.zone)

토큰 저장소를 지운 것이 효과가 있었습니다.

로컬 스토리지를 확인합니다.정의되지 않은 값이 있는 것 같습니다. 그래서 이 오류가 발생한 것입니다.

누군가에게 도움이 된다면, 저는 제 주의 일부를 인수로 하여 콜백 함수를 호출하려고 할 때 비슷한 문제가 있었습니다.내 결심은 컴포넌트 마운트에 대한 약속 후에 그것을 호출하는 것이었다.이것이 당신의 코드에 대한 정확한 해결책은 아니지만 다른 사람에게 도움이 될 수 있습니다.

componentDidMount() {
    const { clientId } = this.props
    axios.get(`/api/getpayments/${clientId}`)
        .then(response => {
            this.setState({ payments: response.data })
        })
        .then(() => {
            this.props.updateProgressBar(this.state.payments.slice())
        })
}

토큰 개체를 확인합니다. 로컬 스토리지에는 정의되어 있지 않을 수 있습니다. 그걸 없애면 모든 게 잘 될 거야토큰을 저장하는 로컬 저장소 또는 쿠키를 지웁니다.

말 그대로 https://reactjs.org/docs/cross-origin-errors.html,에서 가장 먼저 언급되는 사항이지만, 다른 누군가가 먼저 여기에 왔을 경우를 대비해서:

<script crossorigin src="..."></script>

페이지가 아닌 다른 도메인에서 번들을 서비스하는 경우에 필요합니다.예. 때리고 있었어요.localhost:8040웹 팩 개발 서버에서 번들을 처리합니다.localhost:3000

콘텍스트스토어가 정의되지 않은 localStorage에서 뭔가에 액세스하려고 했기 때문에 같은 에러가 몇 번이고 발생하고 있었습니다.콘텍스트 API를 사용하여 이 오류를 발견한 사람이 있을 경우 localStorage를 클리어하면 위의 많은 답변에서 설명한 바와 같이 도움이 될 수 있습니다. : )

이 행에 대해서, 다음의 에러가 표시되는 경우가 있습니다.

console.log('SubmitZone: ' + JSON.stringify(this.state.zone))

이.state를 캐스팅하려고 합니다.문자열 유형 값(null이거나 비어 있거나 형식이 올바르지 않은 경우)으로 영역화

"localStorage를 지웁니다.local Storage가 필요한 경우...

localStorage에 액세스하는 각 지점을 검토하는 것이 좋습니다.각 입력 및 출력 지점을 확인합니다. 입력 및 출력이 예상대로인지 확인합니다. 즉, 출력이 있을 뿐만 아니라 어떤 유형인지도 확인합니다.

예를 들어 토큰을 가지고 있고,JSON.parse(yourToken)토큰이 문자열이 아니거나 문자열화되지 않았거나...이 에러가 발생합니다.

브라우저에 의해 발생할 수 있습니다.

브라우저를 닫고 열었습니다.내 문제는 해결됐어

가능하면 렌더링 또는 상태 JSON.parse("your data")를 사용하지 마십시오.이 문제는 mycomponent에서 삭제되었습니다.

이 에러는, 전화했을 때에 발생합니다.setState콜백 함수 내부에서.에러가 발생하는 동안setState실제 에러는, 다음에 오는 것, 즉 DOM 렌더링(에 의해서 개시됨)으로부터 발생합니다.setState).

componentDidMount() {  
    if (this.state.songs.length === 0) 
        fetch("/collection/tracks")
        .then(res => res.json())
        .then(data => {
            this.setState({
                songs: data
            });
        });
}

렌더링에서 재할당 컬프라이트인 JSON 날짜를 해석하려고 했습니다.JSON 데이터 스트링이 아닌 것 같습니다.

{new Date(JSON.parse(song.added_at)).toLocaleDateString()}

@Jim의 대답처럼: 다음 코드도 보세요.

에러가 나는 이유는JSON.parse(localStorage.getItem("user") || '');문제는 만약JSON.parse()포맷이 올바르지 않습니다.이 에러가 발생하고 있습니다.

이렇게 작은 따옴표로 빈 개체를 전달한 것이 유일한 변경 사항입니다.'{}'

이하와 같이

JSON.parse(localStorage.getItem("user") || '{}');<==============>

리액트 리듀스로 코드 작업을 하다가 샌드박스에서도 같은 문제가 발생하였습니다.직접 전화하실 때마다this.props.anymethod()이 에러로 되돌립니다.로컬에서 처리하도록 하고, 그 후 내부에서 소품 방법을 공략합니다.

다음과 같은 경우:

나는 이 시나리오에서 교차원 문제를 해결했다.

로컬 스토리지에서 토큰을 지우는 것이 도움이 되었습니다.

다른 브라우저 인스턴스에서 응용 프로그램 창을 닫으면 이 오류에 도움이 될 수 있습니다.특히, 이 에러는, https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS 에 기재되어 있는 브라우저의 동작은 다음과 같습니다.

이는 보안상의 문제로 인해 React가 오류의 트레이스백을 표시하지 않기 때문에 표시됩니다.이 오류는 모두 CORS와 관련이 없을 수 있습니다.콘솔에 표시되는 오류가 없는지 확인하는 것이 좋습니다.이러한 오류를 해결하면 문제가 해결될 수 있습니다.

놀랍게도 콤마가 잘못되어 로컬 스토리지에 문제가 발생했습니다.

과 같이 됩니다.{ "myVar":true, }개발 환경을 새로고침하면 이 오류가 발생합니다.정상으로 되돌아가기 위해 필요한 것은 그것을 제거하는 것 뿐이었다.

React의 페이지에서 제안하는 솔루션이 다른 접근방식을 제안하고 있기 때문에 로컬 스토리지 테스트를 할 때 이를 상기하고 같은 문제를 해결할 수 있도록 답변으로 문서화합니다.

로컬 스토리지를 취급할 때는 테이크 아웃에 주의해 주십시오.

몇개, 이 데이터를 사용하여 를 개발 하려고 할 때 합니다.JSON.parse()★★★★★★ 。

localStorage.setItem("user",user); //store as object

const user = JSON.parse(localStorage.getItem("user")); // trying to convert to object

JSON.parse()를 사용하여 javascript 객체를 해석하고 있는지 확인합니다.react.js에서 이런 유형의 오류가 발생할 수 있습니다.

, 된 것은 '이러다', '이러다', '이러다'를입니다.let/const내 변수들 중 하나에 대해서요

언급URL : https://stackoverflow.com/questions/48611310/uncaught-error-a-cross-origin-error-was-thrown-react-doesnt-have-access-to-th

반응형