source

유형 오류 해결 방법: 정의되지 않거나 null을 개체로 변환할 수 없습니다.

factcode 2023. 10. 1. 22:00
반응형

유형 오류 해결 방법: 정의되지 않거나 null을 개체로 변환할 수 없습니다.

JSON.stringify()를 효과적으로 복제하여 값의 범위를 문자열화된 버전으로 변환하는 몇 가지 함수를 작성했습니다.JSBin으로 코드를 포팅하여 샘플 값으로 실행하면 정상적으로 작동합니다.하지만 이를 테스트하기 위해 설계된 스펙 러너에서 이 오류가 발생하고 있습니다.

내 코드:

  // five lines of comments
  var stringify = function(obj) {
  if (typeof obj === 'function') { return undefined;}  // return undefined for function
  if (typeof obj === 'undefined') { return undefined;} // return undefined for undefined
  if (typeof obj === 'number') { return obj;} // number unchanged
  if (obj === 'null') { return null;} // null unchanged
  if (typeof obj === 'boolean') { return obj;} // boolean unchanged
  if (typeof obj === 'string') { return '\"' + obj + '\"';} // string gets escaped end-quotes
  if (Array.isArray(obj)) { 
    return obj.map(function (e) {  // uses map() to create new array with stringified elements
        return stringify(e);
    });
  } else {
    var keys = Object.keys(obj);   // convert object's keys into an array
    var container = keys.map(function (k) {  // uses map() to create an array of key:(stringified)value pairs
        return k + ': ' + stringify(obj[k]);
    });
    return '{' + container.join(', ') + '}'; // returns assembled object with curly brackets
  }
};

var stringifyJSON = function(obj) {
    if (typeof stringify(obj) != 'undefined') {
        return "" + stringify(obj) + "";
    }
};

테스터로부터 받는 오류 메시지는 다음과 같습니다.

TypeError: Cannot convert undefined or null to object
    at Function.keys (native)
    at stringify (stringifyJSON.js:18:22)
    at stringifyJSON (stringifyJSON.js:27:13)
    at stringifyJSONSpec.js:7:20
    at Array.forEach (native)
    at Context.<anonymous> (stringifyJSONSpec.js:5:26)
    at Test.Runnable.run (mocha.js:4039:32)
    at Runner.runTest (mocha.js:4404:10)
    at mocha.js:4450:12
    at next (mocha.js:4330:14)

strigifyJSON(null)과 함께 실패하는 것 같습니다.

총대답

오류는 예를 들어 개체를 인수로 예상하지만 대신 정의되지 않거나 null을 전달하는 함수를 호출할 때 발생합니다.

Object.keys(null)
Object.assign(window.UndefinedVariable, {})

이는 일반적으로 실수에 의한 것이므로 해결책은 코드를 확인하고 null/undefined 조건을 수정하여 함수가 적절한 Object를 얻거나 아예 호출되지 않도록 하는 것입니다.

Object.keys({'key': 'value'})
if (window.UndefinedVariable) {
    Object.assign(window.UndefinedVariable, {})
}

문제의 코드에 해당하는 답변

if (obj === 'null') { return null;} // null unchanged 것입니다.null에만, "null" 을 하면.null스크립트의 value, 코드의 Object 부분에서 구문 분석됩니다. 그리고Object.keys(null)를 던지다TypeError언급된.고치기 위해서는.if(obj === null) {return null}도 내지 말입니다. --

개체가 비어 있지 않은지(null 또는 정의되지 않음) 확인합니다.

오류:

let obj

Object.keys(obj)

해결책:

Object.keys(obj || {})

있지 합니다()null아니면undefined).

다음과 같이 빈 개체로 대상 개체를 초기화할 수 있습니다.

var destinationObj = {};

Object.assign(destinationObj, sourceObj);

null 또는 정의되지 않은 개체의 속성에 액세스할 때 오류를 방지하는 데 매우 유용합니다.

null에서 정의되지 않은 개체로

const obj = null;
const newObj = obj || undefined;
// newObj = undefined

빈 개체로 정의되지 않음

const obj; 
const newObj = obj || {};
// newObj = {}     
// newObj.prop = undefined, but no error here

개체를 비울 null

const obj = null;
const newObj = obj || {};
// newObj = {}  
// newObj.prop = undefined, but no error here

Object &&객체를 맵에 올리기 전에 작동합니다.

objexts && Object.keys(objexts)?.map((objext, idx) => 

저의 경우, 크롬에 루시드 확장 기능을 추가했는데 당시에는 문제를 인지하지 못했습니다.약 하루 동안 문제를 해결하고 프로그램을 뒤집은 후, 누군가가 게시물에서 루시드를 언급했습니다.나는 내가 했던 일을 기억하고 크롬에서 확장자를 제거하고 다시 프로그램을 실행했습니다.문제가 사라졌습니다.저는 리액트와 함께 일하고 있습니다.이게 도움이 될 거라 생각했어요.

저는 리액트 네이티브 프로젝트에서도 같은 문제를 해결했습니다.이걸 이용해서 풀었어요.

let data = snapshot.val();
if(data){
  let items = Object.values(data);
}
else{
  //return null
}

교체하다

if (typeof obj === 'undefined') { return undefined;} // return undefined for undefined
if (obj === 'null') { return null;} // null unchanged

와 함께

if (obj === undefined) { return undefined;} // return undefined for undefined 
if (obj === null) { return null;} // null unchanged

라라벨을 이용하시는 거라면, 제 문제는 제 루트라는 이름에 있었습니다.대신:

Route::put('/reason/update', 'REASONController@update');

다음과 같이 적었습니다.

Route::put('/reason/update', 'RESONController@update');

컨트롤러 이름을 고쳤을 때 코드가 작동했습니다!

저 같은 경우에는 한 쌍의 괄호가 더 있었습니다.()

대신에

export default connect(
  someVariable
)(otherVariable)()

그럴 수 밖에 없었습니다.

export default connect(
  someVariable
)(otherVariable)

아래 토막글은 제가 어떻게 같은 문제를 겪었지만 다른 시나리오에서 어떻게 해결했는지, 그리고 어떻게 수락된 답변의 지침을 사용하여 해결했는지 이해하기에 충분합니다.제 경우에는 Object.keys() 메서드를 사용하여 'defaultViewData' 배열의 0번째 인덱스에 있는 개체의 키를 기록하려고 했습니다.

defaultViewData = [{"name": "DEFAULT_VIEW_PLP","value": {"MSH25": "LIST"}}] 

console.log('DEFAULT_VIEW', Object.keys(this.props.defaultViewData[0]));

console.log가 인쇄되지 않아 이 질문에 게시된 것과 동일한 오류가 발생했습니다.그 오류를 방지하기 위해 아래 조건을 추가했습니다.

    if(this.props.defaultViewData[0]) {
  console.log('DEFAULT_VIEW', Object.keys(this.props.defaultViewData[0]));
}

이 체크를 추가하면 이 오류가 발생하지 않습니다.누군가에게 도움이 되었으면 좋겠습니다.

참고: React.js 코드입니다.(비록 문제를 이해하는 것은 중요하지 않습니다.

reactTraverser.js:6 UncaughtTypeError: 함수에서 정의되지 않거나 null을 개체로 변환할 수 없습니다.reactTraverser.js:6의 키()

스크립트 형식에서 이 오류가 발생하는 경우 Live Server 없이 사용해 보십시오. 이 오류는 표시되지 않습니다.

제 API 요청이 만료되어 이 오류가 발생하는 null 값을 전달하고 있었습니다.

API 제한을 확인하는 것이 좋습니다. 여기에 이미지 설명을 입력하십시오.

웹 형태의 요소에 대해서도 같은 문제가 있습니다.그래서 제가 수정한 것은 validate였습니다. 만약 (Object === 'null') 뭔가를 한다면

언급URL : https://stackoverflow.com/questions/29721205/how-to-resolve-typeerror-cannot-convert-undefined-or-null-to-object

반응형