The 18-year-old Fernandez capitalised as Osaka lost her cool to craft a remarkable 5-7 7-6 (7-2) 6-4 victory.
Osaka was broken as she served for the match in the second set, and a poor tie-break handed Fernandez the initiative under the New York lights.
The teenager could not contain her smile as she secured a fantastic win.
Osaka never regained her composure after she was broken in the second set, twice throwing her racquet to the floor as the tie-break flew away from her.
Fernandez broke her in the opening game of the third set and used her powerful forehand to muscle her way to victory.
She will face another Grand Slam champion in Angelique Kerber in the fourth round.
“From the very beginning I knew I was able to win,” Fernandez said.
“I wasn’t focusing on Naomi, I was just focusing on what I needed to do. The crowd made a huge difference – they helped me get the win.”
Osaka has had a difficult past few months and took an eight-week break to protect her mental health after speaking openly about her struggles with depression.
She has had limited time on court, playing just five matches in the past two months, and received a walkover into the third round in New York after her opponent withdrew.
For the first set and for the majority of the second, Osaka looked in control, despite Fernandez matching her with her forehand and strong serving.
Serving for the match at 6-5, Osaka lost her rhythm, handing Fernandez a crucial break as she sent a forehand long.
The tie-break quickly went away from the two-time US Open champion, Osaka gesturing at herself and the court as the crowd rallied behind her opponent.
World number 70 Fernandez was a complete contrast to Osaka, celebrating her strong shot play and pumping the air as a miss down the line from Osaka sent the match to a decider.
Osaka spent the third set changeovers with a towel over her head, trying to regain her composure, but her frustration was still evident as she went down an early break and had to stave off two break points to avoid going 3-0 down.
While she showed glimpses of her best form, she could not force a break point on the Fernandez serve, with the teenager feeding off the crowd.
Osaka was booed as she made Fernandez wait with the teenager 30-0 up and serving for the match, but the Canadian responded with a drop shot winner to garner three match points. She needed just one, turning and celebrating as Osaka sent a cross-court forehand wide. (Courtesy BBC)