Raphinha scored twice, and Lamine Yamal and Eric García added a goal each for Barcelona, who had trailed 2-0 after Mbappe scored in the fifth and 14th minutes at Montjuic stadium.
But the hosts levelled Sunday's match just over the half-hour mark, and went on to lead 4-2 at halftime in a sensational recovery.
Mbappe then completed his hat-trick in the 70th minute but Madrid weren't able to come back in a likely fatal blow to their hopes of successfully defending the title.
Mbappe became the league's leading scorer with 27 goals, two more than Barcelona's Robert Lewandowski, who did not start on Sunday.
It was another thrilling match involving Barcelona, who on Tuesday had been eliminated 7-6 on aggregate by Inter Milan in extra time in the semi-finals of the Champions League.
The Catalan club have won every match against Madrid this season, having already won 4-0 at the Bernabeu Stadium in the first league match in October, 5-2 in the Spanish Super Cup final in January, and 3-2 in the Copa del Rey final last month.
"We have to celebrate the victory. I'm very happy for the whole club and the fans. The atmosphere is incredible, and I really appreciate it," Barcelona coach Hansi Flick said. "The job isn't finished yet. We need to be more consistent defensively, but with matches every three days it's very difficult to train."
Barcelona can clinch the title by winning at Espanyol on Thursday. They could already be champions by then if Madrid fail to beat Mallorca on Wednesday.
Barcelona then host Villarreal and visit Athletic Bilbao in the final round.
The result, which virtually ends Madrid's hopes of finishing the season with a title, adds pressure on coach Carlo Ancelotti, who is rumoured to be leaving the club to take over Brazil's national team.
Former Madrid player Xabi Alonso, who recently announced he is leaving Bayer Leverkusen, is widely expected to be Madrid's next coach.
Needing to win to get back into the title race, Madrid got off to a great start before Barcelona responded.
García started Barcelona's comeback with a header off a corner kick in the 19th, Yamal equalised with a curling shot into the far corner in the 32nd, and Raphinha scored in the 34th and 45th minutes for Barcelona.
It was a mistake by Barcelona defender Pau Cubarsi that had led to the early penalty converted by Mbappe for the first Madrid goal, and the French superstar added another goal in a breakaway to give the visitors a 2-0 lead.
Both teams had goals disallowed in the final minutes, but Barcelona are now unbeaten in 16 straight league matches, with their last loss coming against Atletico Madrid late last year.